A FastAPI-based backend for a citizen complaint management platform that leverages AI for automatic categorization and intelligent duplicate detection.
✅ Multi-Modal Complaint Submission - Accept text, images, and audio
✅ AI-Powered Categorization - Automatic categorization using Gemini AI
✅ Real-Time Status Tracking - Track complaints from submission to resolution
✅ Department Management - Role-based access for different municipal departments
✅ Interactive Map Integration - GeoJSON endpoints for Leaflet.js
✅ Duplicate Detection - Smart similarity matching to identify duplicate complaints
✅ Analytics Dashboard - Comprehensive insights for authorities
- FastAPI - Modern Python web framework
- MongoDB - Database with geospatial capabilities
- Motor - Async MongoDB driver
- Cloudinary - Cloud storage for images and audio
- Google Gemini AI - Multi-modal AI for categorization
- Pydantic - Data validation
Techyothon-backend/
├── app.py # Main FastAPI application
├── config.py # Configuration management
├── database.py # MongoDB connection
├── models.py # Pydantic models and schemas
├── requirements.txt # Python dependencies
├── .env # Environment variables (create this)
├── routers/
│ ├── complaints.py # Complaint submission & retrieval
│ ├── status.py # Status tracking endpoints
│ ├── departments.py # Department management
│ ├── map.py # Map & location endpoints
│ └── analytics.py # Analytics & statistics
├── services/
│ ├── cloudinary_service.py # File upload service
│ ├── gemini_service.py # AI categorization
│ └── similarity_service.py # Duplicate detection
└── middleware/
└── cors.py # CORS configuration
# Create virtual environment (if not already created)
python -m venv venv
# Activate virtual environment
# On Windows:
venv\Scripts\activate
# On Mac/Linux:
source venv/bin/activate
# Install dependencies
pip install -r requirements.txtCreate a .env file in the root directory:
# MongoDB Configuration
MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/?retryWrites=true&w=majority
DATABASE_NAME=smart_problem_resolver
# Cloudinary Configuration
CLOUDINARY_CLOUD_NAME=your_cloud_name
CLOUDINARY_API_KEY=your_api_key
CLOUDINARY_API_SECRET=your_api_secret
# Gemini AI Configuration
GEMINI_API_KEY=your_gemini_api_key
# Application Settings
APP_NAME=Smart Problem Resolver
APP_VERSION=1.0.0- Go to MongoDB Atlas
- Create a free cluster
- Get your connection string
- Important: URL-encode special characters in password (e.g.,
#becomes%23)
- Go to Cloudinary
- Sign up for free account
- Get Cloud Name, API Key, and API Secret from dashboard
- Go to Google AI Studio
- Create an API key
- Copy the key to your
.envfile
# Development mode with auto-reload
python app.py
# Or using uvicorn directly
uvicorn app:app --reload --host 0.0.0.0 --port 8000The API will be available at http://localhost:8000
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
POST /api/complaints/submit- Submit new complaint (multipart form-data)GET /api/complaints/{complaint_id}- Get complaint detailsGET /api/complaints/user/{user_id}- Get user's complaintsGET /api/complaints/{complaint_id}/similar- Find similar complaints
PATCH /api/complaints/{complaint_id}/status- Update complaint statusPOST /api/complaints/{complaint_id}/verify- Verify resolutionGET /api/complaints/{complaint_id}/history- Get status history
GET /api/departments/{dept_name}/complaints- Get department complaintsGET /api/departments/{dept_name}/complaints/pending- Get pending complaintsPATCH /api/departments/assign/{complaint_id}- Assign to departmentGET /api/departments/{dept_name}/stats- Department statistics
GET /api/map/complaints- Get complaints in GeoJSON formatGET /api/map/heatmap- Get heatmap dataGET /api/map/nearby- Find nearby complaintsGET /api/map/clusters- Get complaint clusters
GET /api/analytics/dashboard- Overall analytics dashboardGET /api/analytics/category/{category}- Category-specific analyticsGET /api/analytics/department/{department}- Department analytics
curl -X POST "http://localhost:8000/api/complaints/submit" \
-F "title=Pothole on Main Street" \
-F "description=Large pothole causing traffic issues" \
-F "latitude=12.9716" \
-F "longitude=77.5946" \
-F "address=Main Street, Bangalore" \
-F "user_id=user123" \
-F "image=@pothole.jpg"const formData = new FormData();
formData.append('title', 'Pothole on Main Street');
formData.append('description', 'Large pothole causing traffic issues');
formData.append('latitude', 12.9716);
formData.append('longitude', 77.5946);
formData.append('address', 'Main Street, Bangalore');
formData.append('user_id', 'user123');
formData.append('image', fileInput.files[0]);
const response = await fetch('http://localhost:8000/api/complaints/submit', {
method: 'POST',
body: formData
});
const result = await response.json();
console.log(result);pothole- Road potholesgarbage- Garbage overflow/collection issuesstreetlight- Street light problemsdrainage- Drainage and sewage issueswater_leakage- Water pipe leakspower_outage- Power supply issuesother- Other civic issues
- Submitted - Initial complaint submission
- Assigned - Assigned to department
- In Progress - Work in progress
- Resolved - Issue resolved
- Citizen can verify resolution
- Roads Department - Handles potholes
- Sanitation Department - Handles garbage issues
- Electricity Department - Handles streetlights and power outages
- Water Department - Handles drainage and water leakage
- Other - Handles miscellaneous issues
Gemini AI analyzes the complaint title, description, and image to:
- Automatically categorize the issue
- Determine priority level (low, medium, high, critical)
- Extract relevant insights
The system uses:
- Location-based clustering - Groups complaints within 50m radius
- Text similarity - Compares complaint descriptions
- Category matching - Only compares similar issue types
- Time window - Checks recent complaints (last 7 days)
MongoDB's geospatial features enable:
- Finding nearby complaints
- Generating heatmaps
- Creating complaint clusters
- Bounding box queries for map views
Get insights on:
- Complaint trends over time
- Resolution rates by department
- High-complaint areas
- Category distribution
- Priority breakdown
curl http://localhost:8000/healthcurl -X POST "http://localhost:8000/api/complaints/submit" \
-F "title=Test Pothole" \
-F "description=Testing the system" \
-F "latitude=12.9716" \
-F "longitude=77.5946"curl "http://localhost:8000/api/map/complaints?category=pothole"If you see import errors, ensure you've installed all dependencies:
pip install -r requirements.txt- Check if MongoDB URI is correct in
.env - Ensure password is URL-encoded (special characters like
#should be%23) - Verify network access in MongoDB Atlas (add your IP to whitelist)
- Verify credentials in
.env - Check if file size is within limits
- Ensure file type is supported (JPEG, PNG for images)
- Verify API key is valid
- Check if you have quota available
- Ensure image URLs are accessible
uvicorn app:app --reloaduvicorn app:app --port 8080Set reload=True in app.py or use the --reload flag
For production deployment:
- Set proper CORS origins in
middleware/cors.py - Use environment variables for all secrets
- Enable HTTPS
- Use a production-ready MongoDB instance
- Set up proper logging
- Configure rate limiting
- Use a reverse proxy (nginx)
MIT License - Built for Techyothon Hackathon 2024
For issues or questions, please check the API documentation at /docs or contact the development team.