<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sdivyasree on Medium]]></title>
        <description><![CDATA[Stories by Sdivyasree on Medium]]></description>
        <link>https://medium.com/@sdivyasree2002?source=rss-ba87948cc4d3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*xZU2Pti4M5PqZHvf</url>
            <title>Stories by Sdivyasree on Medium</title>
            <link>https://medium.com/@sdivyasree2002?source=rss-ba87948cc4d3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 05:41:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sdivyasree2002/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[AI Complaint Analyzer: How to Build a Smarter Civic Complaint System]]></title>
            <link>https://medium.com/@sdivyasree2002/ai-complaint-analyzer-how-to-build-a-smarter-civic-complaint-system-f5c2f016335e?source=rss-ba87948cc4d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/f5c2f016335e</guid>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[dashboard]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[smart-cities]]></category>
            <dc:creator><![CDATA[Sdivyasree]]></dc:creator>
            <pubDate>Tue, 25 Nov 2025 06:53:18 GMT</pubDate>
            <atom:updated>2025-11-25T06:53:18.604Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction | Overview</h3><p>Every day, citizens file hundreds of complaints about civic issues — power outages, thefts, accidents, medical emergencies — but many of these go unprioritized or unresolved because of manual bottlenecks. <strong>AI Complaint Analyzer</strong> is a cloud-native application designed to transform how civic complaints are handled: it classifies, prioritizes, summarizes, and recommends actions for each complaint using Google Generative AI (Gemini-2.5-flash), reducing manual effort and accelerating response.</p><h3>Problem Statement</h3><p>Manual complaint management is slow, error-prone, and resource intensive:</p><ul><li>Governments or municipal offices receive free‑text complaints with no structured data.</li><li>Critical complaints (e.g., medical emergencies, accidents) can be buried among routine issues.</li><li>Administrators lack insights into complaint trends, priority distribution, or real-time status.</li></ul><p>These challenges result in delayed responses, misallocations, and poor citizen satisfaction.</p><p><strong>The following are the objectives that were accomplished:</strong></p><ol><li>Understand how to build a cloud-based AI system for automating civic complaint analysis.</li><li>Learn how to integrate FastAPI with Google Gemini AI for categorizing complaints and detecting priorities.</li><li>Gain hands-on knowledge of storing, retrieving, and managing complaint data using Firestore.</li><li>Be able to implement a frontend dashboard with tables, filters, search, pagination, CSV export, and visual charts for complaints.</li><li>Learn how to evaluate AI performance using metrics like <strong>Precision, Recall, and F1 score</strong>.</li><li>Understand how to deploy the application on <strong>Cloud Run</strong> and make it scalable.</li></ol><h3>Proposed Solution</h3><p>AI Complaint Analyzer streamlines the entire complaint lifecycle:</p><ol><li><strong>Submission</strong>: Citizens submit complaints via a simple frontend or API.</li><li><strong>AI Processing</strong>: The backend forwards the complaint to Gemini (or a fallback classifier), which returns structured JSON including:</li></ol><ul><li><strong>Category</strong> (Theft, Accident, Power, Medical, Unknown)</li><li><strong>Priority</strong> (Critical, High, Medium, Low)</li><li><strong>Summary</strong></li><li><strong>Suggested Action</strong></li></ul><p><strong>3. Storage &amp; Status Tracking</strong>: Complaints are saved to a Firestore / database along with status (“New”, “In-Progress”, “Resolved”) and timestamps.</p><p><strong>4. Dashboard &amp; Analytics</strong>: Administrators use a dashboard to:</p><ul><li>View complaints in a paginated, filterable table</li><li>Edit priority or status</li><li>Export complaints to CSV</li><li>See aggregated charts (pie charts for category/priority) and trend statistics</li></ul><p><strong>5. Scalable Deployment</strong>: Entire system is deployed on <strong>Google Cloud Run</strong>, ensuring it can scale with demand and handle load gracefully.</p><h3>Design</h3><p>The AI Complaint Analyzer is designed to automate the categorization, prioritization, and management of civic complaints. The architecture is <strong>cloud-native, scalable, and modular</strong>, ensuring fast response times and easy maintainability.</p><h4>Components</h4><ol><li><strong>Frontend (Web Dashboard)</strong></li></ol><ul><li>Built with <strong>HTML, CSS, and JavaScript</strong>, the dashboard allows users to submit complaints, view complaint status, filter/search complaints, and visualize stats via pie charts.</li><li><strong>Rationale:</strong> Separating the frontend allows for a responsive user experience and makes it easier to update the UI without affecting backend logic.</li></ul><ol><li><strong>Backend (FastAPI)</strong></li></ol><ul><li>Handles API requests such as /submit, /update_status, /update_priority, /update_category, /delete_complaint, /health and /stats.</li><li>Processes complaints, communicates with the AI engine, and interacts with the database.</li><li><strong>Rationale:</strong> FastAPI is lightweight, asynchronous, and optimized for high performance, making it ideal for real-time complaint processing.</li></ul><p><strong>2. AI Engine (Google Gemini AI)</strong></p><ul><li>Classifies complaints into categories such as (Police, Municipality, Transport), predicts priority levels (Critical, High, Medium, Low), and generates summaries and suggested actions.</li><li>Includes a <strong>fallback keyword-based system</strong> for cases when AI is unavailable.</li><li><strong>Rationale:</strong> Using a generative AI model ensures smarter, context-aware classification, reducing manual workload.</li></ul><p><strong>3. Database (Firestore)</strong></p><ul><li>Stores all complaint records, including original text, AI-generated category, priority, summary, status, and timestamps.</li><li><strong>Rationale:</strong> Firestore provides real-time updates, easy scalability, and seamless integration with cloud services.</li></ul><p><strong>4. Cloud Deployment (Cloud Run)</strong></p><ul><li>Deploys the FastAPI backend in a <strong>serverless, auto-scaling environment</strong>.</li><li><strong>Rationale:</strong> Cloud Run allows the system to handle varying loads without manual infrastructure management.</li></ul><p><strong>5. Dashboard &amp; Analytics</strong></p><ul><li>Provides <strong>search, filter, pagination, CSV export, and pie charts</strong> for complaints categorized by department and priority.</li><li><strong>Rationale:</strong> Visualizations improve usability, making it easier for authorities to track complaint trends and take timely action.</li></ul><h4>Architecture Flow</h4><ol><li>A user submits a complaint via the web dashboard.</li><li>The FastAPI backend receives the complaint and sends it to the <strong>AI engine</strong> for analysis.</li><li>The AI engine returns a <strong>structured JSON</strong> with category, priority, summary, and suggested action.</li><li>The backend saves this data into <strong>Firestore</strong>.</li><li>The frontend fetches the data from Firestore and displays it in a <strong>dynamic table</strong> with filters, search, and pagination.</li><li>Pie charts visualize complaint distribution by category and priority.</li><li>Cloud Run ensures <strong>auto-scaling</strong> to manage multiple concurrent users.</li></ol><h4>Architecture Diagram</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NkYXxDqrj-dnwxhVYjYGVQ.png" /><figcaption>AI Complaint Analyzer Architecture</figcaption></figure><h4>Design Rationale</h4><ul><li><strong>Separation of Concerns:</strong> Frontend, backend, AI engine, and database are modular, making maintenance and upgrades easier.</li><li><strong>Scalability:</strong> Cloud Run allows the system to handle high traffic without manual intervention.</li><li><strong>Usability:</strong> A clean dashboard with filters, search, CSV export, and charts ensures authorities can easily manage and analyze complaints.</li><li><strong>Reliability:</strong> A fallback keyword system ensures continued operation if AI is temporarily unavailable.</li><li><strong>Extensibility:</strong> Additional AI models or analytics features can be integrated without major redesign.</li></ul><h3>Prerequisites</h3><ul><li><strong>Python 3.10+</strong> — The backend is built with FastAPI.<br> <a href="https://www.python.org/downloads/">Download Python</a></li><li><strong>Virtual Environment</strong> — For managing project dependencies.<br> (Built-in with Python via venv)</li><li><strong>FastAPI Framework</strong> — Handles backend APIs.<br> Installed via pip install fastapi uvicorn</li><li><strong>Google Cloud Account</strong> — Needed for deploying the AI backend on Cloud Run and using Firestore.<br> <a href="https://cloud.google.com/">Sign up for Google Cloud</a></li><li><strong>Firestore Database</strong> — Stores complaints and AI-generated results.</li><li><strong>Google Gemini AI </strong>— Required for AI-powered complaint analysis.</li><li><strong>IDE or Text Editor</strong> — Such as <strong>VS Code.</strong></li><li><strong>Basic Knowledge Assumed:</strong></li><li>Python programming</li><li>REST APIs and HTTP methods (GET, POST)</li><li>JSON data format</li><li>Basic understanding of cloud deployment concepts (Cloud Run, service accounts)</li></ul><h3>Implementation Details</h3><p>Here’s how I have built the system:</p><ul><li><strong>Backend</strong>: Using <strong>FastAPI</strong>, with Pydantic models for cleaner API definitions.</li><li><strong>AI Engine</strong>: Google Gemini (if API key is available), else fallback to lightweight keyword-based classifier.</li><li><strong>Database</strong>: Firestore / Google Cloud DB is used to persist complaints and AI outputs.</li><li><strong>Metrics &amp; Monitoring</strong>: Health endpoint (/health), stats endpoint (/stats), and Locust-based load testing for elasticity.</li><li><strong>Dashboard</strong>: Built with HTML + JS; supports search, filter, pagination, CSV export, and charting.</li></ul><h3>Step-by-Step Guide: Building the AI Complaint Analyzer</h3><p>This section walks you through the key tasks to set up, run, and use the AI Complaint Analyzer.</p><h4>1. Setting Up the Project</h4><ol><li><strong>Clone the repository</strong>:</li></ol><ul><li>git clone https://github.com/yourusername/ai-complaint-analyzer.git cd ai-complaint-analyzer</li></ul><p><strong>2. Create and activate a virtual environment</strong>:</p><ul><li>Linux/Mac:</li><li>python3 -m venv venv source venv/bin/activate</li><li>Windows:</li><li>python -m venv venv .\venv\Scripts\Activate.ps1</li></ul><p><strong>3. Install project dependencies</strong>:</p><ul><li>pip install -r requirements.txt</li></ul><p><strong>4. Set up environment variables</strong></p><ul><li>GEMINI_API_KEY=&lt;your_google_gemini_api_key&gt; GOOGLE_APPLICATION_CREDENTIALS=&lt;path_to_service_account.json&gt; PROJECT_ID=&lt;your_gcloud_project_id&gt;</li></ul><h4>2. Running the Application Locally</h4><ol><li>Start the FastAPI server:</li></ol><p>uvicorn main:app --reload --host 0.0.0.0 --port 8080</p><ol><li>Access the dashboard: <a href="http://localhost:8080/">http://localhost:8080</a><br> Swagger docs: <a href="http://localhost:8080/docs">http://localhost:8080/docs</a></li></ol><blockquote><strong><em>Tip:</em></strong><em> If you encounter missing dependencies, run </em><em>pip install -r requirements.txt again or check Python version compatibility (&gt;=3.9 recommended).</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*w0FjTS0El_p7loDm.png" /><figcaption>AI ompplaint Dashboard</figcaption></figure><h4>3. Submitting Complaints</h4><ol><li>Navigate to the dashboard.</li><li>Enter a complaint in the input box.</li><li>Click <strong>Submit</strong>.</li><li>Observe the AI-generated category, priority, summary, and suggested action appear in the table.</li></ol><blockquote><strong><em>Example complaint:</em></strong><em><br> </em>“There is a power outage in my area for the past 3 hours.”</blockquote><h4>4. Updating Complaints</h4><ul><li><strong>Change Status:</strong> Use the dropdown in the table to update a complaint’s status (New, In-Progress, Resolved).</li><li><strong>Change Priority or Category:</strong> Click the corresponding update buttons or dropdowns to modify priority or category manually.</li></ul><h4>5. Exporting and Analyzing Data</h4><ul><li>Export complaints as a CSV:</li><li>curl &quot;http://localhost:8080/export?status=New&amp;priority=High&quot;</li><li>View dashboard statistics at /stats or the pie charts for priority and category distribution at the bottom of the UI.</li></ul><h4>6. Deploying to Cloud Run</h4><ol><li>Build and submit container image:</li></ol><p>gcloud builds submit --tag gcr.io/&lt;PROJECT_ID&gt;/ai-complaint-analyzer:latest</p><p>2. Deploy to Cloud Run:</p><p>gcloud run deploy ai-complaint-analyzer \ --image gcr.io/&lt;PROJECT_ID&gt;/ai-complaint-analyzer:latest \ --platform managed \ --region europe-west1 \ --allow-unauthenticated</p><p>3. Access your live app using the Cloud Run URL provided after deployment.</p><h3>API Endpoints</h3><p>1. Submit Complaint</p><ul><li>Endpoint: /submit</li><li>Method: POST</li><li>Description: Submits a citizen complaint for AI analysis. The AI classifies the complaint, assigns a priority, summarizes it, and suggests an action.</li><li>Request Body (JSON):</li></ul><pre>{<br>  &quot;complaint&quot;: &quot;Power outage in my area for 3 hours&quot;<br>}</pre><p>Response (JSON):</p><pre>{<br>  &quot;doc_id&quot;: &quot;abc123&quot;,<br>  &quot;category&quot;: &quot;Power&quot;,<br>  &quot;priority&quot;: &quot;Medium&quot;,<br>  &quot;summary&quot;: &quot;Citizen reports: Power outage in my area for 3 hours&quot;,<br>  &quot;suggested_action&quot;: &quot;Notify electricity department&quot;,<br>  &quot;status&quot;: &quot;New&quot;,<br>  &quot;created_at&quot;: &quot;2025-11-24T12:00:00Z&quot;<br>}</pre><p>2. List Complaints</p><ul><li>Endpoint: /complaints</li><li>Method: GET</li><li>Description: Returns a paginated, searchable list of complaints. Supports filtering by status and priority..</li><li>Query Parameters:</li><li>q: search query</li><li>status: filter by status</li><li>priority: filter by priority</li><li>page, page_size: pagination</li><li>sort_by, sort_dir: sorting</li></ul><p>3. Update Status Endpoint</p><ul><li>Endpoint: /update_status</li><li>Method: POST</li><li>Description: Updates the status of a complaint.</li><li>Request Body:</li></ul><pre>{<br>  &quot;doc_id&quot;: &quot;abc123&quot;,<br>  &quot;status&quot;: &quot;In-Progress&quot;<br>  }</pre><p>4. Update Priority Endpoint</p><ul><li>Endpoint: /update_priority</li><li>Method: POST</li><li>Description: Updates the priority of a complaint.</li><li>Request Body:</li></ul><pre>{<br>  &quot;doc_id&quot;: &quot;abc123&quot;,<br>  &quot;priority&quot;: &quot;Critical&quot;<br>  }</pre><p>5. Update Category Endpoint</p><ul><li>Endpoint: /update_category</li><li>Method: POST</li><li>Description: Updates the category of a complaint.</li><li>Request Body:</li></ul><pre>{<br>  &quot;doc_id&quot;: &quot;abc123&quot;,<br>  &quot;category&quot;: &quot;Accident&quot;<br>  }</pre><p>6. Delete Complaint Endpoint</p><ul><li>Endpoint: /delete_complaint</li><li>Method: POST</li><li>Description: Deletes a complaint.</li><li>Request Body:</li></ul><pre>{<br> &quot;doc_id&quot;: &quot;abc123&quot;<br>  }</pre><p>7. Export CSV</p><ul><li>Endpoint: /export</li><li>Method: GET</li><li>Optional Query Parameters: status, priority</li></ul><p>8. Statistics</p><ul><li>Endpoint: /stats</li><li>Method: GET Returns complaint counts, category distribution, priority distribution, and trends.</li></ul><p>9. Health Check</p><ul><li>Endpoint: /health</li><li>Method: GET</li><li>Response: { “status”: “ok” }</li></ul><p>Dashboard</p><ul><li>Table: Paginated, searchable, sortable</li><li>Charts: Pie charts for category and priority distributions</li><li>CSV Export: Download filtered complaints</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7MSo072xi0ELNOlQFjQzCA.png" /><figcaption>Pie chart</figcaption></figure><h4>AI Performance Metrics</h4><ul><li>Metrics are evaluated using Precision, Recall, and F1-score.</li><li>Use evaluate_ai_metrics.py:</li></ul><pre>python evaluate_ai_metrics.py</pre><ul><li>Sample output</li></ul><pre>=== CATEGORY METRICS ===<br>Theft: Precision=1.00, Recall=0.67, F1=0.80<br>Accident: Precision=1.00, Recall=1.00, F1=1.00<br>Power: Precision=0.00, Recall=0.00, F1=0.00<br>Medical: Precision=0.67, Recall=1.00, F1=0.80<br>Unknown: Precision=1.00, Recall=1.00, F1=1.00</pre><pre>=== PRIORITY METRICS ===<br>Critical: Precision=1.00, Recall=1.00, F1=1.00<br>High: Precision=1.00, Recall=1.00, F1=1.00<br>Medium: Precision=1.00, Recall=1.00, F1=1.00<br>Low: Precision=1.00, Recall=1.00, F1=1.00</pre><pre>=== OVERALL AVERAGE ===<br>Category - Precision=0.96, Recall=0.96, F1=0.96<br>Priority - Precision=1.00, Recall=1.00, F1=1.00</pre><h4>Load &amp; Elasticity Testing</h4><ul><li>Tool: Locust</li><li>Simulate multiple users submitting complaints concurrently</li><li>Validate Cloud Run scaling behavior</li><li>Obaserve cloud Run metrics at: <a href="https://console.cloud.google.com/run/detail/europe-west1/ai-complaint-analyzer/observability/metrics?orgonly=true&amp;project=ai-complaint-analyzer&amp;supportedpurview=organizationId">Cloud_Run_Metrics</a></li></ul><h4>7. Troubleshooting Common Issues</h4><ul><li><strong>Gemini API Key errors:</strong> Verify your GEMINI_API_KEY is correct and active.</li><li><strong>Service account errors:</strong> Ensure GOOGLE_APPLICATION_CREDENTIALS points to a valid JSON file.</li><li><strong>Package version conflicts:</strong> Reinstall dependencies or create a fresh virtual environment.</li></ul><h3>Demo of the result</h3><p>Demo link: <a href="https://drive.google.com/file/d/1ymQvz-voptI63IQD4drhwk5knnZk39Gg/view?usp=sharing">Google Drive</a></p><h3>Challenges &amp; Trade‑offs</h3><ul><li><strong>Data Quality</strong>: AI classification only works well if the complaint text is clear. Ambiguous or multi-issue complaints may be misclassified.</li><li><strong>Synthetic Dataset</strong>: Current evaluation uses limited synthetic test data; real-world complaints can be more messy.</li><li><strong>Bias in Labels</strong>: Defining “priority” can be subjective. What one person considers “Critical” may be “High” for another.</li></ul><h3>Roadmap &amp; Future Work</h3><p>To make the system production-ready and more robust, here’s what’s next:</p><ol><li><strong>Expand Test Dataset</strong></li></ol><ul><li>Add hundreds of real or realistic complaints</li><li>Cover edge cases, ambiguous complaints, mixed issues</li><li>Use multiple human reviewers to label ground truth for category and priority</li></ul><p><strong>2. Refine AI Models / Prompts</strong></p><ul><li>Fine-tune Gemini, or use few-shot prompting to improve accuracy</li><li>Develop fallback logic for fallback classifier when AI fails</li></ul><p><strong>3. Role-Based Access &amp; Notifications</strong></p><ul><li>Enable role-based dashboard access (citizen, admin, department)</li><li>Integrate alerting: send SMS/email for <strong>Critical</strong> complaints</li></ul><p><strong>4. Historical Trend Analytics</strong></p><ul><li>Track complaint volume over time (days/weeks/months)</li><li>Use time-series forecasting to predict complaint surges.</li></ul><h3>Conclusion</h3><p>AI Complaint Analyzer is a powerful step towards smarter and more responsive civic systems. By automating complaint classification, prioritization, and summarization, we can drastically reduce manual workload and ensure <strong>urgent citizen issues are handled promptly</strong>. The next phases of dataset expansion and AI refinement will make the system even more accurate, scalable, and trustworthy — bringing us closer to a future where governments truly listen and act.</p><h3>Call to action</h3><p>To learn more about Google Cloud services and to create impact for the work you do, get around to these steps right away:</p><ul><li>Register for <a href="https://rsvp.withgoogle.com/events/cv">Code Vipassana sessions</a></li><li>Join the meetup group <a href="https://www.meetup.com/datapreneur-social/">Datapreneur Social</a></li><li>Sign up to become <a href="https://cloud.google.com/innovators?utm_source=cloud_sfdc&amp;utm_medium=email&amp;utm_campaign=FY23-1H-vipassana-innovators&amp;utm_content=joininnovators&amp;utm_term=-">Google Cloud Innovator</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5c2f016335e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>