Spaces:
Configuration error
Configuration error
Upload 12 files
Browse filesFiles changed (12)
- .gitattributes+2-35
- .gitignoreAdded+14
- DockerfileAdded+22
- README.md+169-11
- app.jsAdded+211
- app.pyAdded+449
- environment.pyAdded+1050
- index.htmlAdded+203
- inference.pyAdded+446
- openenv.yamlAdded+254
- requirements.txtAdded+5
- styles.cssAdded+639
1234567891011121314151617181920212223242526272829303132333435*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tar filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text12# Auto detect text files and perform LF normalization* text=auto
1234567891011121314# Environment variables
.env
.env.*
# Python cache
__pycache__/
*.pyc
# OS junk
.DS_Store
Thumbs.db
# Logs
*.log12345678910111213141516171819202122# Base image
FROM python:3.10-slim
# Set working directory
WORKDIR /app
# Copy all files into container
COPY . .
# Install dependencies
RUN pip install --no-cache-dir \
flask \
flask-cors \
openai \
pydantic \
python-dotenv
# Expose port (IMPORTANT for HF Spaces)
EXPOSE 7860
# Run app
CMD ["python", "app.py"]1234567891011---title: CivicPulseemoji: 👁colorFrom: purplecolorTo: pinksdk: dockerpinned: falseshort_description: Citizen grievance AI---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169# CivicPulse AI – OpenEnv Civic Grievance Decision Environment## 🐳 Running with DockerThis project includes a Dockerfile so that the entire application can run without manually installing dependencies.### Build the Docker Imagedocker build -t civicpulse-ai .### Run the Applicationdocker run -p 7860:7860 civicpulse-ai### Open in BrowserOnce the container is running, open:http://localhost:7860### Environment VariablesTo use the AI features, create a `.env` file in the root directory:HF_TOKEN=your_api_key_hereMODEL_NAME=openai/gpt-oss-20bAPI_BASE_URL=https://router.huggingface.co/v1Note: The system will still work using rule-based logic if the API key is not provided.### Why Docker?Docker makes it easy to run this project on any system without worrying about setup.Everything (backend, frontend, dependencies) runs inside a single container.## Problem StatementUnstructured civic complaints often lead to incorrect routing, delays,and unresolved issues due to unclear information, multiple problems inone message, and lack of intelligent prioritization.This project models civic grievance handling as a structured decisionenvironment where an agent must interpret complaints, ask clarification,and route them correctly.## SolutionCivicPulse AI converts raw civic complaints into structured decisions.It identifies issues, assigns urgency, determines ownership (public/private),and routes the complaint to the correct authority. It also asks clarificationquestions when the complaint lacks sufficient detail.This system is designed not just as an application, but as an environment forevaluating and improving decision-making agents.## How to Run- Run the backend: python app.py- The application runs on port 7860 (frontend and backend are integrated)- Open http://localhost:7860 in your browser## AI System OverviewThe system processes complaints through multiple steps:- Text preprocessing- Signal extraction (keywords, urgency, legal hints)- Domain classification (Sanitation, Electricity, Infrastructure)- Issue detection (single or multiple)- Clarification (if needed)- Authority mapping- Priority ordering- Reward evaluationThis ensures structured and explainable decision-making instead of random chatbot responses.## Tools Used- Python- Flask (backend API)- OpenEnv framework- Hugging Face / OpenAI-compatible API- Pydantic (typed models)- HTML, CSS, JavaScript (frontend)## Backend (OpenEnv Environment)The backend is implemented as an OpenEnv environment with:- `reset()` → initializes complaint state- `step(action)` → processes agent decision- `state()` → returns current environment stateThe environment fully follows OpenEnv specifications with typed models and deterministic evaluation.### OpenEnv Interaction LoopThe environment follows a standard agent loop:- reset(complaint) → initializes the environment- step(action) → evaluates the decision and returns reward- state() → returns current stateFlow:Observation → Action → Environment → Reward → Next Observation## Working Terminology- HF Token → Used for accessing LLM APIs- LLM Fallback → Rule-based logic used when LLM fails- Observation → processed complaint data- Action → structured decision output- Reward → score assigned to action## Reward SystemThe reward function is deterministic and provides partial credit:- 1.0 → correct domain and authority- 0.5 → correct domain but incorrect authority- 0.3 → safe handling of ambiguous cases (clarification / escalation)- 0.0 → incorrect handlingThis reward design reflects real-world decision quality, where partially correctactions are still valuable and safe handling is preferred over confident mistakes.## FrontendThe frontend simulates a real civic interaction interface where users can submitcomplaints and receive structured decisions.It includes:- Welcome screen with system introduction- Complaint category selection- Chat-based interaction- Structured output display (issues, urgency, authority, recommendation)## Learning Behaviour (Memory)The system includes a lightweight memory mechanism.It stores previous complaints and retrieves similar cases (`memory_hits`) to assistin decision-making.While it does not retrain model weights internally, it provides:- structured observations- deterministic rewards- reproducible tasksAn external agent can use these signals to improve decision-making over time.## Limitations- No real-time government system integration- Limited to predefined domains- Memory is not a full learning system- LLM may fail without valid API token## Scope / Feasibility- Can integrate with government complaint systems- Supports multilingual expansion- Can evolve into a full complaint tracking platform- Suitable for real-world civic automation# Future Features- Ai action layer(sends emails to dept and follows up complaints)- More interactive- Broaden complaint areas- Image upload and Image analyzation by Ai## ConclusionCivicPulse AI demonstrates how real-world civic complaint handling can be transformedinto a structured decision environment.It bridges rule-based reasoning and AI-assisted processing to enable reliable,explainable, and scalable agent evaluation.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211const API_URL = "/analyze";console.log("JS LOADED");console.log("API URL NOW =", API_URL)const chatMessages = document.getElementById("chatMessages");const chatForm = document.getElementById("chatForm");const chatInput = document.getElementById("chatInput");const choicePanel = document.getElementById("choicePanel");const writeOwnBtn = document.getElementById("writeOwnBtn");const choiceButtons = document.querySelectorAll(".choice-btn[data-example]");const sendBtn = document.getElementById("sendBtn");const typingIndicator = document.getElementById("typingIndicator");
let pendingClarification = false;let currentComplaint = "";
/** * Escapes HTML characters to prevent XSS. */function escapeHtml(text) { if (text === null || text === undefined) return ""; return String(text) .replaceAll("&", "&") .replaceAll("<", "<") .replaceAll(">", ">");}
/** * Auto-scroll to the bottom of the chat container. */function scrollToBottom() { chatMessages.scrollTop = chatMessages.scrollHeight;}
/** * Appends a user message to the chat. */function appendUserMessage(text) { const msgDiv = document.createElement("div"); msgDiv.className = "message user"; const contentDiv = document.createElement("div"); contentDiv.className = "message-content"; contentDiv.innerText = text; msgDiv.appendChild(contentDiv); chatMessages.appendChild(msgDiv); scrollToBottom();}
/** * Appends a bot message (HTML supported) to the chat. */function appendBotMessage(htmlContent) { const msgDiv = document.createElement("div"); msgDiv.className = "message bot"; const contentDiv = document.createElement("div"); contentDiv.className = "message-content"; contentDiv.innerHTML = htmlContent; msgDiv.appendChild(contentDiv); chatMessages.appendChild(msgDiv); scrollToBottom();}
function showTyping() { typingIndicator.classList.remove("hidden"); scrollToBottom();}
function hideTyping() { typingIndicator.classList.add("hidden");}
/** * Builds the HTML content for the bot's response incorporating result cards. */function buildResultUI(data) { let html = ""; // 1. Check if clarification is needed if (data.clarification_needed && data.clarification_question) { html += `<p>I need one quick detail before proceeding:</p> <p><strong>${escapeHtml(data.clarification_question)}</strong></p>`; pendingClarification = true; return html; }
// Reset clarification state if not needed pendingClarification = false;
// 2. Normal Response Report html += `<p style="margin-bottom: 0.5rem; font-weight: 500;"> Here’s what I found based on your complaint:</p>`;
if (Array.isArray(data.issues) && data.issues.length > 0) { data.issues.forEach(issue => { const urgencyClass = issue.urgency ? issue.urgency.toLowerCase() : "default"; html += ` <div class="result-card"> <div class="result-header"> <div class="result-title">${escapeHtml(issue.title)}</div> <div class="tag ${urgencyClass}">${escapeHtml(issue.urgency || "UNKNOWN URGENCY")}</div> </div> <div class="authority-highlight"> Assigned Authority: ${escapeHtml(issue.authority || "General Administration")} </div> <div class="reason-text"> ${escapeHtml(issue.reason)} </div>`; const rec = data.final_recommendation || issue.recommendation; if (rec) { html += ` <div class="recommendation-box"> <strong>Recommendation Action</strong> ${escapeHtml(rec)} </div>`; } html += `</div>`; }); } else { html += `<p>We could not identify a valid issue from the request. Please provide more detailed information.</p>`; }
return html;}
/** * Handle form submission */choiceButtons.forEach(button => { button.addEventListener("click", () => { const example = button.dataset.example; chatInput.value = example; chatForm.classList.remove("hidden"); choicePanel.classList.add("hidden"); chatInput.focus(); });});
writeOwnBtn.addEventListener("click", () => { chatInput.value = ""; chatForm.classList.remove("hidden"); choicePanel.classList.add("hidden"); chatInput.focus();});chatForm.addEventListener("submit", async (e) => { e.preventDefault(); const text = chatInput.value.trim(); if (!text) return;
// Render User Message appendUserMessage(text); // Clear & Disable Input chatInput.value = ""; chatInput.disabled = true; sendBtn.disabled = true;
// Show Typing UI showTyping();
try { let payload = {}; if (pendingClarification) { payload = { complaint: currentComplaint, clarification: text, task_id: "" }; } else { currentComplaint = text; // Keep track of the original context payload = { complaint: text, task_id: "" }; }
// Optional delay for a natural feel await new Promise(res => setTimeout(res, 600));
const response = await fetch(API_URL, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({complaint: currentComplaint || text, clarification: pendingClarification ? text: "", task_id: "demo-task" }) });
if (!response.ok) { throw new Error("Server response was not OK."); }
const data = await response.json(); hideTyping(); const botHtml = buildResultUI(data); appendBotMessage(botHtml);
} catch (err) { console.error("API Error:", err); hideTyping(); appendBotMessage(`<p>Frontend error: ${escapeHtml(err.message)}</p>`); } finally { chatInput.disabled = false; sendBtn.disabled = false; chatInput.focus(); }});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449from __future__ import annotations
import jsonimport osfrom typing import Any, Dict, Optional
from flask import Flask, jsonify, request, send_from_directory
try: from flask_cors import CORS # optionalexcept Exception: # pragma: no cover CORS = None
from openai import OpenAIfrom pydantic import ValidationError
from environment import GrievanceEnvironment, Action, IssueUnit
# -----------------------------------------------------------------------------# Flask app setup# -----------------------------------------------------------------------------
APP_DIR = os.path.dirname(os.path.abspath(__file__))
app = Flask(__name__, static_folder=APP_DIR, static_url_path="")if CORS is not None: CORS(app) @app.after_requestdef add_cors_headers(response): response.headers["Access-Control-Allow-Origin"] = "http://127.0.0.1:5500" response.headers["Access-Control-Allow-Headers"] = "Content-Type" response.headers["Access-Control-Allow-Methods"] = "GET, POST, OPTIONS" return response
# -----------------------------------------------------------------------------# LLM configuration# -----------------------------------------------------------------------------
API_BASE_URL = os.getenv("API_BASE_URL") or "https://router.huggingface.co/v1"MODEL_NAME = os.getenv("MODEL_NAME") or "openai/gpt-oss-20b"HF_TOKEN = os.getenv("HF_TOKEN") or os.getenv("API_KEY") or ""
SYSTEM_PROMPT = """You are a civic grievance routing system for Indian municipalities.
Respond with VALID JSON ONLY. No markdown. No explanation outside JSON.
Your job:- analyze the complaint- identify one or more issue units- classify each issue as sanitation, electricity, or infrastructure- assign urgency- assign authority- ask a clarification question only when genuinely needed
Rules:1. Safety > public health > disruption > inconvenience2. Root cause is more important than surface wording3. Public issues -> government authority4. Private internal issues -> local_private_solution5. Legal/ownership disputes -> guidance_only6. If complaint is too vague -> insufficient_information=true
Authority map:- sanitation: - drainage/sewage/garbage -> Nagar Nigam - water supply -> Jal Nigam - contamination -> Pollution Control Board - private plumbing -> Licensed Plumber- electricity: - outage/transformer/voltage -> MPPB - billing/meter -> MPPB - Billing Unit - theft/illegal connection -> MPPB - Vigilance/Enforcement - internal wiring -> Qualified Electrician- infrastructure: - roads/bridges/footpaths -> PWD - illegal construction/encroachment -> Town Planning Department - legal dispute -> Town Planning Department / Legal Aid
Allowed authority_type values:government | local_private_solution | government_appeal | guidance_only | insufficient_information
Output schema:{ "issue_units": [ { "set": "sanitation | electricity | infrastructure", "subtype": "string", "root_cause": "string", "visible_symptom": "string", "public_private": "public | private | disputed | unclear", "urgency": "low | medium | high", "confidence_band": "low | medium | high", "authority_type": "government | local_private_solution | government_appeal | guidance_only | insufficient_information", "authority_name": "string", "reasoning": "string", "clarification_needed": false, "clarification_question": "" } ], "overall_priority_order": [0], "manual_review_recommended": false, "insufficient_information": false, "disclaimer_needed": false}"""
# -----------------------------------------------------------------------------# Helpers# -----------------------------------------------------------------------------
def safe_parse_json(raw: str) -> Dict[str, Any]: """Parse model JSON safely. Return fallback dict on failure.""" fallback = { "issue_units": [], "overall_priority_order": [], "manual_review_recommended": True, "insufficient_information": True, "disclaimer_needed": False, }
if not raw: return fallback
try: data = json.loads(raw) if isinstance(data, dict): return data except json.JSONDecodeError: pass
text = raw.strip()
if text.startswith("```"): lines = [ln for ln in text.splitlines() if not ln.strip().startswith("```")] text = "\n".join(lines).strip() try: data = json.loads(text) if isinstance(data, dict): return data except json.JSONDecodeError: pass
start = text.find("{") end = text.rfind("}") if start != -1 and end != -1 and end > start: try: data = json.loads(text[start:end + 1]) if isinstance(data, dict): return data except json.JSONDecodeError: pass
return fallback
def build_action_from_dict(data: Dict[str, Any]) -> Optional[Action]: """Convert dict into Action. Return None if invalid.""" issue_units = [] raw_units = data.get("issue_units", []) if isinstance(raw_units, list): for item in raw_units[:4]: if not isinstance(item, dict): continue try: issue_units.append( IssueUnit( set=str(item.get("set", "sanitation")), subtype=str(item.get("subtype", "unknown")), root_cause=str(item.get("root_cause", "")), visible_symptom=str(item.get("visible_symptom", "")), public_private=str(item.get("public_private", "unclear")), urgency=str(item.get("urgency", "low")), confidence_band=str(item.get("confidence_band", "low")), authority_type=str(item.get("authority_type", "insufficient_information")), authority_name=str(item.get("authority_name", "Unknown")), reasoning=str(item.get("reasoning", "")), clarification_needed=bool(item.get("clarification_needed", False)), clarification_question=str(item.get("clarification_question", "")), ) ) except ValidationError: continue
priority = data.get("overall_priority_order", list(range(len(issue_units)))) if not isinstance(priority, list): priority = list(range(len(issue_units)))
try: return Action( issue_units=issue_units, overall_priority_order=priority, manual_review_recommended=bool(data.get("manual_review_recommended", False)), insufficient_information=bool(data.get("insufficient_information", False)), disclaimer_needed=bool(data.get("disclaimer_needed", False)), ) except ValidationError: return None
def call_llm(observation) -> str: """Call LLM if token exists. Raise RuntimeError when unavailable.""" if not HF_TOKEN: raise RuntimeError("No HF_TOKEN/API_KEY configured")
client = OpenAI(api_key=HF_TOKEN, base_url=API_BASE_URL)
user_message = ( f"COMPLAINT:\n{observation.raw_text}\n\n" f"PROCESSED TEXT:\n{observation.processed_text}\n\n" f"DETECTED DOMAINS: {observation.possible_sets}\n" f"KEYWORDS: {observation.extracted_signals.keywords}\n" f"HAZARD CLUES: {observation.extracted_signals.hazard_clues}\n" f"OWNERSHIP CLUES: {observation.extracted_signals.ownership_clues}\n" f"LEGAL CLUES: {observation.extracted_signals.legal_clues}\n" f"RULE-BASED URGENCY: {observation.extracted_signals.urgency_level}\n" f"LOCATION: {observation.location}\n\n" f"SIMILAR PAST CASES:\n" f"{json.dumps(observation.memory_hits, ensure_ascii=False, indent=2)}\n\n" "Return JSON only." )
completion = client.chat.completions.create( model=MODEL_NAME, temperature=0.0, max_tokens=1800, messages=[ {"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": user_message}, ], )
content = completion.choices[0].message.content return content.strip() if content else ""
def format_issue_title(subtype: str) -> str: mapping = { "water_supply": "Water Supply Problem", "water_contamination": "Water Contamination", "drainage_blockage": "Drainage Blockage", "sewage_overflow": "Sewage Overflow", "garbage_collection": "Garbage Collection Issue", "power_outage": "Power Outage", "voltage_fluctuation": "Voltage Fluctuation", "transformer_fault": "Transformer Fault", "billing_dispute": "Electricity Billing Issue", "electricity_theft": "Electricity Theft / Illegal Connection", "internal_wiring": "Internal Wiring Issue", "road_damage": "Road Damage", "bridge_damage": "Bridge Damage", "footpath_obstruction": "Footpath Obstruction", "illegal_construction": "Illegal Construction", "building_issue": "Unsafe Building Issue", "general_sanitation": "Sanitation Issue", "general_infrastructure": "Infrastructure Issue", "general_electricity": "Electricity Issue", } return mapping.get(subtype, subtype.replace("_", " ").title())
def to_ui_payload(action: Action, reward_result, note: Optional[str]) -> Dict[str, Any]: issues = [] clarification_question = ""
for unit in action.issue_units: issues.append({ "title": format_issue_title(unit.subtype), "set": unit.set.title(), "subtype": unit.subtype, "urgency": unit.urgency.title(), "ownership": unit.public_private.title(), "authority": unit.authority_name, "authority_type": unit.authority_type.replace("_", " ").title(), "reason": unit.root_cause or unit.reasoning or "Complaint suggests a civic issue requiring attention.", })
if unit.clarification_needed and unit.clarification_question.strip() and not clarification_question: clarification_question = unit.clarification_question.strip()
recommendation = "" if issues: idx = action.overall_priority_order[0] if action.overall_priority_order else 0 idx = idx if 0 <= idx < len(issues) else 0 top_issue = issues[idx] recommendation = f"Recommended next step: contact your local {top_issue['authority']} office " f"or register a complaint through the official civic helpline for the " f"{top_issue['title'].lower()}." elif action.insufficient_information: recommendation = "Please provide a clearer complaint so the system can route it correctly."
return { "status": "ok", "clarification_needed": bool(clarification_question), "clarification_question": clarification_question, "issues": issues, "priority_order": action.overall_priority_order, "feedback": reward_result.feedback, "reward_score": reward_result.score, "final_recommendation": recommendation, "manual_review_recommended": action.manual_review_recommended, "insufficient_information": action.insufficient_information, "backend_note": note or "", }
# -----------------------------------------------------------------------------# Routes# -----------------------------------------------------------------------------
@app.get("/")def index() -> Any: return send_from_directory(APP_DIR, "index.html")
@app.get("/app.js")def serve_js() -> Any: return send_from_directory(APP_DIR, "app.js")
@app.get("/styles.css")def serve_css() -> Any: return send_from_directory(APP_DIR, "styles.css")
CURRENT_ENV = GrievanceEnvironment()CURRENT_OBS = None
@app.route("/reset", methods=["POST"])def reset_env(): global CURRENT_ENV, CURRENT_OBS
data = request.get_json(silent=True) or {} complaint = str(data.get("complaint", "")).strip() task_id = str(data.get("task_id", "")).strip() or None
if not complaint: complaint = "No water supply in my area since morning."
CURRENT_ENV = GrievanceEnvironment() CURRENT_OBS = CURRENT_ENV.reset(complaint, task_id=task_id)
return jsonify({ "observation": CURRENT_OBS.model_dump() })
@app.route("/step", methods=["POST"])def step_env(): global CURRENT_ENV
data = request.get_json(silent=True) or {} action_data = data.get("action", {}) or {}
action = Action(**action_data) observation, reward, done, info = CURRENT_ENV.step(action)
return jsonify({ "observation": observation.model_dump(), "reward": reward.model_dump(), "done": done, "info": info })
@app.route("/state", methods=["GET"])def get_state(): global CURRENT_ENV return jsonify(CURRENT_ENV.state())
@app.route("/analyze", methods=["POST","OPTIONS"])def analyze() -> Any: if request.method == "OPTIONS": response = jsonify({}) response.status_code = 200 return response payload = request.get_json(silent=True) or {} complaint = str(payload.get("complaint", "")).strip() clarification = str(payload.get("clarification", "")).strip() task_id = str(payload.get("task_id", "")).strip() or None
if not complaint: return jsonify({"status": "error", "message": "Complaint text is required."}), 400
merged_text = complaint
if clarification: clar = clarification.lower()
if any(k in clar for k in ("poori", "whole", "building", "colony", "area")): merged_text += " whole area"
elif any(k in clar for k in ("ghar", "house", "home", "flat", "room")): merged_text += " house only"
if any(k in clar for k in ("public", "road", "street")): merged_text += " public place"
if any(k in clar for k in ("near", "location", "paas")): merged_text += f" location {clar}"
env = GrievanceEnvironment() observation = env.reset(merged_text, task_id=task_id)
action: Optional[Action] = None note: Optional[str] = None
action = GrievanceEnvironment.build_rule_based_action(observation) note = "Rule-based decision mode." print("ACTION OBJECT:", action) print("ISSUE UNITS:", action.issue_units) print("DEBUG clarification flags:") for unit in action.issue_units: print(unit.subtype, unit.clarification_needed, unit.clarification_question) _, reward_result, _, _ = env.step(action) print("DEBUG action issue units:", len(action.issue_units)) for unit in action.issue_units: print( "DEBUG unit:", unit.subtype, "| clarify =", unit.clarification_needed, "| question =", unit.clarification_question ) try: observation = env.reset(merged_text, task_id=task_id) action = GrievanceEnvironment.build_rule_based_action(observation)
# prepare response FIRST response = { "clarification_needed": action.issue_units[0].clarification_needed, "clarification_question": action.issue_units[0].clarification_question, "message": "Processed successfully" }
return jsonify(response)
except Exception as e: print("ERROR:", e) return jsonify({ "clarification_needed": False, "message": "Server error" }), 500
if __name__ == "__main__": app.run(host="0.0.0.0", port=7860)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050"""
environment.py — OpenEnv Civic Grievance Decision Environment
Production-ready structured decision environment for complaint handling.
"""
from __future__ import annotations
import re
import unicodedata
from typing import List, Optional, Dict, Any, Tuple
from pydantic import BaseModel, Field
# ---------------------------------------------------------------------------
# Pydantic Models
# ---------------------------------------------------------------------------
class IssueUnit(BaseModel):
set: str # sanitation | electricity | infrastructure
subtype: str
root_cause: str
visible_symptom: str
public_private: str # public | private | disputed | unclear
urgency: str # low | medium | high
confidence_band: str # low | medium | high
authority_type: str # government | local_private_solution | government_appeal | guidance_only | insufficient_information
authority_name: str
reasoning: str
clarification_needed: bool
clarification_question: str
class Action(BaseModel):
issue_units: List[IssueUnit]
overall_priority_order: List[int]
manual_review_recommended: bool
insufficient_information: bool
disclaimer_needed: bool
class ExtractedSignals(BaseModel):
keywords: List[str]
hazard_clues: List[str]
ownership_clues: List[str]
domain_clues: List[str]
urgency_level: str
scale_clues: List[str]
legal_clues: List[str]
class Observation(BaseModel):
raw_text: str
processed_text: str
possible_sets: List[str]
extracted_signals: ExtractedSignals
location: Optional[str] = None
image_tags: Optional[List[str]] = None
memory_hits: List[Dict[str, Any]] = Field(default_factory=list)
class RewardResult(BaseModel):
score: float
breakdown: Dict[str, float]
feedback: str
# ---------------------------------------------------------------------------
# In-memory Precedent Store
# ---------------------------------------------------------------------------
PRECEDENT_STORE: List[Dict[str, Any]] = [
{
"keywords": ["nali", "drain", "sewage", "naali", "blockage"],
"set": "sanitation",
"subtype": "drainage_blockage",
"precedent_subtype": "drainage_blockage",
"authority_name": "Nagar Nigam",
"urgency": "medium",
"public_private": "public",
},
{
"keywords": ["bijli", "electricity", "light", "power", "current"],
"set": "electricity",
"subtype": "power_outage",
"precedent_subtype": "power_outage",
"authority_name": "MPPB",
"urgency": "medium",
"public_private": "public",
},
{
"keywords": ["transformer", "blast", "fire", "explosion"],
"set": "electricity",
"subtype": "transformer_fault",
"precedent_subtype": "transformer_fault",
"authority_name": "MPPB",
"urgency": "high",
"public_private": "public",
},
{
"keywords": ["road", "sadak", "pothole", "khada", "toot"],
"set": "infrastructure",
"subtype": "road_damage",
"precedent_subtype": "road_damage",
"authority_name": "PWD",
"urgency": "medium",
"public_private": "public",
},
{
"keywords": ["garbage", "kachra", "waste", "dump", "dustbin"],
"set": "sanitation",
"subtype": "garbage_collection",
"precedent_subtype": "garbage_collection",
"authority_name": "Nagar Nigam",
"urgency": "low",
"public_private": "public",
},
{
"keywords": ["water", "paani", "supply", "tap", "pani"],
"set": "sanitation",
"subtype": "water_supply",
"precedent_subtype": "water_supply",
"authority_name": "Jal Nigam",
"urgency": "high",
"public_private": "public",
},
{
"keywords": ["encroachment", "illegal", "construction"],
"set": "infrastructure",
"subtype": "illegal_construction",
"precedent_subtype": "illegal_construction",
"authority_name": "Town Planning Department",
"urgency": "medium",
"public_private": "disputed",
},
{
"keywords": ["meter", "bill", "overcharge", "bijli", "billing"],
"set": "electricity",
"subtype": "billing_dispute",
"precedent_subtype": "billing_dispute",
"authority_name": "MPPB — Billing Unit",
"urgency": "low",
"public_private": "private",
},
{
"keywords": ["wiring", "wire", "internal", "short", "circuit"],
"set": "electricity",
"subtype": "internal_wiring",
"precedent_subtype": "internal_wiring",
"authority_name": "Qualified Electrician",
"urgency": "high",
"public_private": "private",
},
{
"keywords": ["contamination", "gandha", "smell", "dirty", "dirtwater"],
"set": "sanitation",
"subtype": "water_contamination",
"precedent_subtype": "water_contamination",
"authority_name": "Pollution Control Board",
"urgency": "high",
"public_private": "public",
},
{
"keywords": ["theft", "chor", "connection", "illegal", "meter"],
"set": "electricity",
"subtype": "electricity_theft",
"precedent_subtype": "electricity_theft",
"authority_name": "MPPB — Vigilance/Enforcement",
"urgency": "medium",
"public_private": "public",
},
{
"keywords": ["voltage", "fluctuation", "unstable"],
"set": "electricity",
"subtype": "voltage_fluctuation",
"precedent_subtype": "voltage_fluctuation",
"authority_name": "MPPB",
"urgency": "medium",
"public_private": "public",
},
]
# ---------------------------------------------------------------------------
# Domain Signal Maps
# ---------------------------------------------------------------------------
SANITATION_KEYWORDS = {
"sewage", "drain", "nali", "naali", "gutter", "sewer", "overflow", "blockage",
"garbage", "kachra", "waste", "dump", "dustbin", "sweeping", "cleaning",
"water", "paani", "pani", "supply", "tap", "pipeline", "leakage", "leak",
"contamination", "gandha", "smell", "stench", "dirty", "pollution", "malba",
"drainage", "nalaa", "nala", "flood", "waterlogging", "overflowing",
}
ELECTRICITY_KEYWORDS = {
"bijli", "electricity", "electric", "light", "power", "current", "voltage",
"transformer", "meter", "wire", "wiring", "outage", "cut", "shutdown",
"overcharge", "bill", "theft", "chor", "spark", "short", "circuit",
"blackout", "fluctuation", "generator", "pole", "line", "cable",
}
INFRASTRUCTURE_KEYWORDS = {
"road", "sadak", "pothole", "khada", "toot", "broken", "crack",
"construction", "illegal", "encroachment", "kabja",
"bridge", "pul", "footpath", "pavement", "wall", "boundary",
"demolish", "dilapidated", "structure", "repair", "patchwork",
"drainage", "storm", "gutter", "culvert",
}
HAZARD_KEYWORDS = {
"fire", "blast", "explosion", "accident", "death", "emergency", "danger",
"hazard", "risk", "unsafe", "children", "sick", "hospital", "life",
"toxic", "poisonous", "chemical", "gas", "fumes", "electrocution",
"khatra", "injury", "hurt", "medical",
}
OWNERSHIP_PUBLIC = {
"road", "sadak", "nali", "public", "sarkari", "government", "municipal",
"colony", "ward", "mohalla", "street", "park", "school", "hospital",
}
OWNERSHIP_PRIVATE = {
"ghar", "house", "home", "flat", "apartment", "shop", "office",
"internal", "inside", "personal", "private", "apna", "mere",
}
LEGAL_KEYWORDS = {
"illegal", "encroachment", "violation", "dispute", "case", "court",
"complaint", "FIR", "police", "law", "regulation", "permit",
"unauthorized", "license", "ownership", "title",
}
TYPO_MAP = {
"bijlee": "bijli",
"bejli": "bijli",
"biijli": "bijli",
"nalli": "nali",
"naalli": "naali",
"paanee": "paani",
"sadakk": "sadak",
"garbase": "garbage",
"elecrticity": "electricity",
"electrcity": "electricity",
"tranformer": "transformer",
"transfromer": "transformer",
"drainge": "drainage",
"drainege": "drainage",
"encroachement": "encroachment",
"encroachment": "encroachment",
"ilegal": "illegal",
"constuction": "construction",
}
# ---------------------------------------------------------------------------
# Preprocessing
# ---------------------------------------------------------------------------
def normalize_text(text: str) -> str:
"""Lowercase, strip accents, collapse whitespace, fix known typos."""
text = text.strip()
text = unicodedata.normalize("NFKD", text)
text = text.lower()
# Collapse multiple spaces/newlines
text = re.sub(r"\s+", " ", text)
# Fix common typos
for wrong, right in TYPO_MAP.items():
text = re.sub(r"\b" + re.escape(wrong) + r"\b", right, text)
return text
def extract_location(text: str) -> Optional[str]:
"""Heuristic location extraction."""
patterns = [
r"(?:in|at|near|ward|sector|block|colony|mohalla|area)\s+([\w\s]+?)(?:\.|,|$)",
r"(?:ward\s*no\.?\s*\d+)",
]
for pattern in patterns:
match = re.search(pattern, text, re.IGNORECASE)
if match:
return match.group(0).strip()
return None
# ---------------------------------------------------------------------------
# Signal Extraction
# ---------------------------------------------------------------------------
def extract_signals(processed_text: str) -> ExtractedSignals:
words = set(re.findall(r"\b\w+\b", processed_text))
domain_clues = []
if words & SANITATION_KEYWORDS:
domain_clues.append("sanitation")
if words & ELECTRICITY_KEYWORDS:
domain_clues.append("electricity")
if words & INFRASTRUCTURE_KEYWORDS:
domain_clues.append("infrastructure")
hazard_clues = list(words & HAZARD_KEYWORDS)
ownership_public = list(words & OWNERSHIP_PUBLIC)
ownership_private = list(words & OWNERSHIP_PRIVATE)
ownership_clues = (
["public"] * len(ownership_public) + ["private"] * len(ownership_private)
)
legal_clues = list(words & LEGAL_KEYWORDS)
# Urgency level
if hazard_clues or any(k in processed_text for k in ("fire", "blast", "death", "emergency", "khatra")):
urgency_level = "high"
elif any(k in processed_text for k in ("days", "weeks", "long time", "frequent", "regular")):
urgency_level = "medium"
else:
urgency_level = "low"
# Scale clues
scale_clues = []
if re.search(r"\b(many|multiple|all|entire|whole|sab|poori)\b", processed_text):
scale_clues.append("large_scale")
if re.search(r"\b(my|mere|apna|single|one)\b", processed_text):
scale_clues.append("single_household")
keywords = list(
(words & SANITATION_KEYWORDS)
| (words & ELECTRICITY_KEYWORDS)
| (words & INFRASTRUCTURE_KEYWORDS)
)
return ExtractedSignals(
keywords=keywords,
hazard_clues=hazard_clues,
ownership_clues=ownership_clues,
domain_clues=domain_clues,
urgency_level=urgency_level,
scale_clues=scale_clues,
legal_clues=legal_clues,
)
# ---------------------------------------------------------------------------
# Precedent Matching
# ---------------------------------------------------------------------------
def match_precedents(keywords: List[str]) -> List[Dict[str, Any]]:
hits = []
kw_set = set(keywords)
for record in PRECEDENT_STORE:
overlap = kw_set & set(record["keywords"])
if overlap:
hits.append({
"matched_keywords": list(overlap),
"precedent_set": record["set"],
"precedent_subtype": record.get("precedent_subtype", record.get("subtype", "")),
"precedent_authority": record["authority_name"],
"precedent_urgency": record["urgency"],
"precedent_public_private": record["public_private"],
})
# Sort by overlap size descending so strongest match is first
hits.sort(key=lambda h: len(h["matched_keywords"]), reverse=True)
return hits[:3]
# ---------------------------------------------------------------------------
# Rule-Based Issue Detection
# ---------------------------------------------------------------------------
def detect_possible_sets(signals: ExtractedSignals, processed_text: str) -> List[str]:
possible = list(signals.domain_clues)
# Additional heuristics for ambiguous text
if not possible:
if re.search(r"\b(dark|andhera|light nahi|no light)\b", processed_text):
possible.append("electricity")
if re.search(r"\b(smell|stench|rot)\b", processed_text):
possible.append("sanitation")
return list(dict.fromkeys(possible)) # deduplicate preserving order
def infer_public_private(signals: ExtractedSignals) -> str:
pub = signals.ownership_clues.count("public")
priv = signals.ownership_clues.count("private")
if pub > priv:
return "public"
if priv > pub:
return "private"
if signals.legal_clues:
return "disputed"
return "unclear"
def determine_authority(
domain: str,
public_private: str,
subtype: str,
legal_clues: List[str],
) -> Tuple[str, str]:
"""Returns (authority_type, authority_name)."""
# Fix 5: Base guidance_only on actual legal_clues presence + ownership ambiguity,
# not string matching on public_private value.
has_legal = len(legal_clues) > 0
ownership_ambiguous = public_private in ("disputed", "unclear")
if has_legal and ownership_ambiguous:
return "guidance_only", "Legal Aid / Consumer Forum"
if domain == "sanitation":
if public_private == "private":
return "local_private_solution", "Licensed Plumber"
if "contamination" in subtype or "pollution" in subtype:
return "government", "Pollution Control Board"
if "water" in subtype:
return "government", "Jal Nigam"
return "government", "Nagar Nigam"
if domain == "electricity":
if public_private == "private" or "internal" in subtype or "wiring" in subtype:
return "local_private_solution", "Qualified Electrician"
# Fix 4: Separate billing/meter from theft/enforcement
if "billing" in subtype or "meter" in subtype:
return "government", "MPPB — Billing Unit"
if "theft" in subtype:
return "government", "MPPB — Vigilance/Enforcement"
return "government", "MPPB"
if domain == "infrastructure":
# Fix 5: Use legal_clues directly, not string matching
if has_legal:
return "guidance_only", "Town Planning Department / Legal Aid"
if "encroachment" in subtype or "illegal" in subtype:
return "government", "Town Planning Department"
if "road" in subtype or "bridge" in subtype or "footpath" in subtype:
return "government", "PWD"
return "government", "Nagar Nigam"
return "insufficient_information", "Unknown"
def apply_precedent_hints(
domain: str,
subtype: str,
urgency: str,
public_private: str,
authority_name: str,
memory_hits: List[Dict[str, Any]],
confidence: str = "medium",
) -> Tuple[str, str, str, str]:
"""
Use precedent memory to refine subtype, urgency, public_private, and authority_name.
Fix 1: Uses precedent_subtype key (not precedent_set).
Fix 2: Only applies precedent when overlap >= 2 OR confidence is low/medium.
Does not override already-specific subtypes.
Returns updated (subtype, urgency, public_private, authority_name).
"""
# Subtypes that are considered generic — eligible for precedent override
generic_subtypes = {
"general_sanitation", "general_infrastructure", "general_electricity",
"power_outage", "unknown",
}
urgency_rank = {"low": 0, "medium": 1, "high": 2}
for hit in memory_hits:
if hit.get("precedent_set") != domain:
continue
overlap_count = len(hit.get("matched_keywords", []))
# Fix 2: Only apply if overlap >= 2 OR confidence is weak
if overlap_count < 2 and confidence not in ("low", "medium"):
continue
# Fix 1 & 2: Only override subtype when current is generic
precedent_subtype = hit.get("precedent_subtype", subtype)
if subtype in generic_subtypes and precedent_subtype not in generic_subtypes:
subtype = precedent_subtype
# Escalate urgency if precedent signals higher urgency
p_urgency = hit.get("precedent_urgency", urgency)
if urgency_rank.get(p_urgency, 0) > urgency_rank.get(urgency, 0):
urgency = p_urgency
# Use precedent ownership only if current is unclear
if public_private == "unclear":
p_pp = hit.get("precedent_public_private", "unclear")
if p_pp != "unclear":
public_private = p_pp
# Use precedent authority only if current is a generic fallback name
p_auth = hit.get("precedent_authority", "")
generic_authorities = {"Unknown", "Nagar Nigam", "MPPB", "PWD"}
if p_auth and authority_name in generic_authorities:
authority_name = p_auth
break # Apply only the strongest (first) qualifying precedent
return subtype, urgency, public_private, authority_name
# Semantic duplicate groups: if more specific subtype is present, drop the generic alias
_SANITATION_SPECIFICITY_ORDER = [
"water_contamination", # more specific than water_supply
"sewage_overflow", # more specific than drainage_blockage
"drainage_blockage",
"water_supply",
"garbage_collection",
"general_sanitation",
]
_ELECTRICITY_SPECIFICITY_ORDER = [
"transformer_fault",
"internal_wiring",
"electricity_theft",
"billing_dispute",
"voltage_fluctuation",
"power_outage",
"general_electricity",
]
_INFRASTRUCTURE_SPECIFICITY_ORDER = [
"illegal_construction",
"bridge_damage",
"footpath_obstruction",
"road_damage",
"general_infrastructure",
]
# Pairs where the first makes the second redundant
_SANITATION_SUPERSEDES = {
"water_contamination": {"water_supply"}, # contamination implies water is present
"sewage_overflow": {"drainage_blockage"}, # sewage overflow is a type of blockage
}
_ELECTRICITY_SUPERSEDES: Dict[str, set] = {}
_INFRASTRUCTURE_SUPERSEDES: Dict[str, set] = {}
def _deduplicate_subtypes(candidates: List[str], domain: str) -> List[str]:
"""
Fix 3: Remove semantically redundant subtypes.
If a more specific subtype is present, drop its generic alias.
"""
if len(candidates) <= 1:
return candidates
supersedes_map: Dict[str, set] = {}
if domain == "sanitation":
supersedes_map = _SANITATION_SUPERSEDES
elif domain == "electricity":
supersedes_map = _ELECTRICITY_SUPERSEDES
elif domain == "infrastructure":
supersedes_map = _INFRASTRUCTURE_SUPERSEDES
to_remove: set = set()
candidate_set = set(candidates)
for specific, redundant_set in supersedes_map.items():
if specific in candidate_set:
to_remove |= redundant_set & candidate_set
return [c for c in candidates if c not in to_remove]
# Fix 6: Detect multiple issue units within the same domain
def detect_issue_candidates(processed_text: str, domain: str) -> List[str]:
"""
Returns a deduplicated list of subtypes detected within a single domain.
Allows multiple issue units per domain (up to 2 per domain, 4 total).
"""
candidates = []
if domain == "sanitation":
if any(k in processed_text for k in ("drain", "nali", "naali", "blockage", "overflow")):
candidates.append("drainage_blockage")
if any(k in processed_text for k in ("garbage", "kachra", "waste", "dump")):
candidates.append("garbage_collection")
if any(k in processed_text for k in ("water", "paani", "pani", "tap", "supply", "pipeline")):
if any(k in processed_text for k in ("dirty", "contamination", "smell", "gandha", "toxic")):
candidates.append("water_contamination")
else:
candidates.append("water_supply")
if any(k in processed_text for k in ("sewage", "sewer")):
candidates.append("sewage_overflow")
if not candidates:
candidates.append("general_sanitation")
elif domain == "electricity":
if any(k in processed_text for k in ("transformer", "blast", "fire", "explosion")):
candidates.append("transformer_fault")
if any(k in processed_text for k in ("wire", "wiring", "short", "circuit", "internal")):
candidates.append("internal_wiring")
if any(k in processed_text for k in ("meter", "bill", "overcharge")):
candidates.append("billing_dispute")
if any(k in processed_text for k in ("theft", "chor")):
candidates.append("electricity_theft")
if any(k in processed_text for k in ("voltage", "fluctuation")):
candidates.append("voltage_fluctuation")
if not candidates:
candidates.append("power_outage")
elif domain == "infrastructure":
# Special building logic (avoid false positives)
if "building" in processed_text and any(k in processed_text for k in [
"collapse", "collapsing", "crack", "unsafe",
"illegal", "construction", "encroachment"
]):
candidates.append("building_issue")
if any(k in processed_text for k in ("road", "sadak", "pothole", "khada", "toota")):
candidates.append("road_damage")
if any(k in processed_text for k in ("encroachment", "kabja", "illegal", "unauthorized")):
candidates.append("illegal_construction")
if any(k in processed_text for k in ("bridge", "pul")):
candidates.append("bridge_damage")
if any(k in processed_text for k in ("footpath", "pavement")):
candidates.append("footpath_obstruction")
if not candidates:
candidates.append("general_infrastructure")
# Fix 3: Remove semantic duplicates before returning
return _deduplicate_subtypes(candidates, domain)
def infer_subtype(domain: str, processed_text: str) -> str:
"""Return the primary (first) subtype for a domain. Kept for backward compatibility."""
candidates = detect_issue_candidates(processed_text, domain)
return candidates[0] if candidates else "unknown"
def needs_clarification(domain: str, signals: ExtractedSignals, processed_text: str):
text = processed_text.lower()
# Water
if domain == "sanitation" and any(k in text for k in ("pani", "water", "jal")):
if not any(k in text for k in ("area", "poore", "whole", "building", "colony", "ghar", "house")):
return True, "Is the water issue only in your house or in the whole area?"
# Electricity
if domain == "electricity" and any(k in text for k in ("bijli", "electricity", "light", "power")):
if not any(k in text for k in ("area", "poore", "whole", "building", "colony", "ghar", "house")):
return True, "Is the electricity issue only in your house or in the whole area?"
# Infrastructure (FIXED)
if domain == "infrastructure":
# Detect damage keywords (signal it's a problem)
if any(k in text for k in ("toot", "damage", "broken", "crack", "pothole", "khadda", "gadda")):
# Check if scale is unclear
if not any(k in text for k in ("area", "poore", "whole", "colony", "street", "near", "location")):
return True, "Where exactly is the damage? Please specify the area or location."
# Construction ambiguity
if any(k in text for k in ("construction", "building", "structure")):
if not any(k in text for k in ("illegal", "encroachment", "permission", "approved")):
return True, "Is this construction authorized or illegal?"
return False, ""
def is_invalid_input(raw_text: str, processed_text: str) -> bool:
"""
Check if input is vague, abusive, or irrelevant.
Fix 6: If no domain keyword AND no contextual pattern AND < 6 words → invalid.
If >= 6 words but unclear → allow through (clarification will be triggered).
"""
words = processed_text.split()
# Too short to be a meaningful complaint regardless of content
if len(words) < 3:
return True
# Check for domain keywords (token-level)
token_set = set(words)
domain_overlap = (
(token_set & SANITATION_KEYWORDS)
| (token_set & ELECTRICITY_KEYWORDS)
| (token_set & INFRASTRUCTURE_KEYWORDS)
)
if domain_overlap:
return False
# Check for contextual action/complaint phrases (Hinglish, verbs, negations)
contextual_patterns = [
r"\b(nahi|nahin|nah[i]?)\b",
r"\b(band|kharab|toot|broken|aa\s+rahi|aa\s+raha|mil\s+raha)\b",
r"\b(problem|issue|complaint|fix|repair|request)\b",
r"\b(se|hai|hain|ho|kar|hua|hui)\b",
r"\b(no|not|without)\s+\w+",
r"\b(since|days?|weeks?|months?|hours?)\b",
r"\b(help|please|urgent|immediately|asap)\b",
]
has_context = any(re.search(p, processed_text) for p in contextual_patterns)
if has_context:
return False
# Fix 6: < 6 words with no signal → invalid; >= 6 words → allow, trigger clarification
if len(words) < 6:
return True
return False
# ---------------------------------------------------------------------------
# Task Definitions
# ---------------------------------------------------------------------------
TASKS = {
"easy": {
"id": "easy_001",
"description": "Simple single-domain complaint",
"complaint": "The street drain near ward 5 is completely blocked and overflowing onto the road causing flooding.",
"expected_set": "sanitation",
"expected_subtype": "drainage_blockage",
"expected_authority_type": "government",
"expected_authority_name": "Nagar Nigam",
"expected_urgency": "medium",
"expected_public_private": "public",
},
"medium": {
"id": "medium_001",
"description": "Typo-heavy mixed issue complaint",
"complaint": "The bijlee has been cut since 2 days and also the nalli in front is overflowing with dirty water making it very smelly.",
"expected_sets": ["electricity", "sanitation"],
"expected_authority_names": ["MPPB", "Nagar Nigam"],
"expected_urgency": "medium",
},
"hard": {
"id": "hard_001",
"description": "Ambiguous legal case requiring guidance_only",
"complaint": "My neighbour has done illegal construction and encroachment on the public pathway but the municipal office is not listening and I want to take legal action.",
"expected_set": "infrastructure",
"expected_subtype": "illegal_construction",
"expected_authority_type": "guidance_only",
"expected_public_private": "disputed",
},
}
# ---------------------------------------------------------------------------
# Environment
# ---------------------------------------------------------------------------
def generate_reason_text(domain: str, subtype: str, text: str) -> str:
if domain == "sanitation" and subtype == "water_supply":
return "Complaint indicates a disruption in public water supply."
if domain == "electricity" and subtype == "power_outage":
return "Complaint suggests a power outage affecting the area."
if domain == "electricity" and subtype == "voltage_fluctuation":
return "Complaint indicates unstable voltage supply."
if domain == "infrastructure" and subtype == "road_damage":
return "Complaint indicates damage to public road infrastructure."
if domain == "infrastructure" and subtype == "illegal_construction":
return "Complaint suggests unauthorized or illegal construction activity."
if domain == "infrastructure" and subtype == "building_issue":
return "Complaint suggests a potentially unsafe building condition."
return "Complaint suggests a civic issue requiring attention."
class GrievanceEnvironment:
"""OpenEnv-compatible civic grievance routing environment."""
def __init__(self):
self._state: Optional[Dict[str, Any]] = None
self._current_observation: Optional[Observation] = None
self._current_task: Optional[str] = None
self._step_count: int = 0
def reset(self, complaint: str, task_id: Optional[str] = None) -> Observation:
"""Reset environment with a new complaint."""
self._step_count = 0
self._current_task = task_id
processed = normalize_text(complaint)
location = extract_location(processed)
signals = extract_signals(processed)
possible_sets = detect_possible_sets(signals, processed)
memory_hits = match_precedents(signals.keywords)
observation = Observation(
raw_text=complaint,
processed_text=processed,
possible_sets=possible_sets,
extracted_signals=signals,
location=location,
image_tags=None,
memory_hits=memory_hits,
)
self._current_observation = observation
self._state = {
"phase": "awaiting_action",
"step": 0,
"observation": observation.model_dump(),
}
return observation
def step(self, action: Action) -> Tuple[Observation, RewardResult, bool, Dict[str, Any]]:
"""Process an action and return (observation, reward, done, info)."""
if self._current_observation is None or self._state is None:
raise RuntimeError("Call reset() before step().")
self._step_count += 1
# Compute reward
reward = self._compute_reward(action)
# Update state
self._state["phase"] = "completed"
self._state["step"] = self._step_count
self._state["last_action"] = action.model_dump()
self._state["reward"] = reward.model_dump()
done = True # Single-step environment
info = {
"step_count": self._step_count,
"task_id": self._current_task,
"clarifications_pending": any(
u.clarification_needed for u in action.issue_units
),
}
return self._current_observation, reward, done, info
def state(self) -> Dict[str, Any]:
"""Return current environment state."""
return self._state or {}
def _compute_reward(self, action: Action) -> RewardResult:
"""Discrete reward computation."""
if self._current_task is None:
return RewardResult(
score=0.0,
breakdown={},
feedback="No task loaded - cannot evaluate reward.",
)
if self._current_task not in TASKS:
return RewardResult(
score=0.0,
breakdown={},
feedback=f"Unknown task: {self._current_task}",
)
task = TASKS[self._current_task]
breakdown: Dict[str, float] = {}
if self._current_task == "easy":
if not action.issue_units:
return RewardResult(score=0.0, breakdown={}, feedback="No issue units produced.")
unit = action.issue_units[0]
set_correct = unit.set == task["expected_set"]
auth_correct = unit.authority_type == task["expected_authority_type"]
if set_correct and auth_correct:
breakdown["set_match"] = 0.5
breakdown["authority_match"] = 0.5
score = 1.0
feedback = "Correct domain and authority."
elif set_correct:
breakdown["set_match"] = 0.5
breakdown["authority_mismatch"] = 0.0
score = 0.5
feedback = "Correct domain but wrong authority."
elif action.insufficient_information:
score = 0.3
feedback = "Escalated to unknown — partial credit."
breakdown["escalation"] = 0.3
else:
score = 0.0
feedback = "Incorrect domain and authority."
breakdown["incorrect"] = 0.0
elif self._current_task == "medium":
expected_sets = set(task.get("expected_sets", []))
found_sets = {u.set for u in action.issue_units}
overlap = found_sets & expected_sets
if len(overlap) == len(expected_sets):
score = 1.0
feedback = "All domains correctly identified."
breakdown["domain_coverage"] = 1.0
elif overlap:
score = 0.5
feedback = f"Partially correct — identified {overlap}."
breakdown["partial_domain"] = 0.5
else:
score = 0.0
feedback = "No correct domains identified."
breakdown["incorrect"] = 0.0
elif self._current_task == "hard":
if not action.issue_units:
return RewardResult(score=0.0, breakdown={}, feedback="No issue units produced.")
unit = action.issue_units[0]
set_correct = unit.set == task["expected_set"]
auth_correct = unit.authority_type == task["expected_authority_type"]
if set_correct and auth_correct:
score = 1.0
breakdown["set_match"] = 0.5
breakdown["guidance_only_correct"] = 0.5
feedback = "Correctly identified legal case requiring guidance_only."
elif set_correct:
score = 0.5
breakdown["set_match"] = 0.5
feedback = "Correct domain but wrong authority type for legal case."
elif action.insufficient_information or action.manual_review_recommended:
score = 0.3
breakdown["escalation"] = 0.3
feedback = "Escalated — partial credit."
else:
score = 0.0
breakdown["incorrect"] = 0.0
feedback = "Incorrect handling of ambiguous legal case."
else:
score = 0.0
feedback = "Unknown task."
breakdown = {}
return RewardResult(score=score, breakdown=breakdown, feedback=feedback)
@staticmethod
def build_rule_based_action(observation: Observation) -> Action:
"""
Pure rule-based action builder (no LLM).
Detects multiple issue units within the same domain.
Uses precedent memory to influence subtype, urgency, and authority.
"""
processed = observation.processed_text
signals = observation.extracted_signals
memory_hits = observation.memory_hits
if is_invalid_input(observation.raw_text, processed):
return Action(
issue_units=[],
overall_priority_order=[],
manual_review_recommended=True,
insufficient_information=True,
disclaimer_needed=False,
)
possible_sets = observation.possible_sets
if not possible_sets:
return Action(
issue_units=[],
overall_priority_order=[],
manual_review_recommended=True,
insufficient_information=True,
disclaimer_needed=False,
)
issue_units: List[IssueUnit] = []
urgency_rank = {"high": 0, "medium": 1, "low": 2}
has_precedent = bool(memory_hits)
for domain in possible_sets:
if len(issue_units) >= 4:
break
subtypes = detect_issue_candidates(processed, domain)
for subtype in subtypes:
if len(issue_units) >= 4:
break
public_private = infer_public_private(signals)
# Fix 4: Improved confidence using keyword count, hazard, and precedent
kw_count = len(signals.keywords)
if (kw_count > 3 and has_precedent) or signals.hazard_clues:
confidence = "high"
elif kw_count > 1 or has_precedent:
confidence = "medium"
else:
confidence = "low"
urgency = signals.urgency_level
# Safety-first urgency override
if signals.hazard_clues:
urgency = "high"
# Derive initial authority before precedent
authority_type, authority_name = determine_authority(
domain, public_private, subtype, signals.legal_clues
)
# Apply precedent hints (Fix 1 & 2 already embedded in function)
subtype, urgency, public_private, authority_name = apply_precedent_hints(
domain, subtype, urgency, public_private, authority_name,
memory_hits, confidence
)
# Re-derive authority_type after precedent may have changed public_private
# Only re-derive type; use precedent authority_name if it was updated
authority_type, derived_name = determine_authority(
domain, public_private, subtype, signals.legal_clues
)
# Keep the precedent-refined authority_name unless determine_authority
# returned a more specific one (i.e., not a generic fallback)
generic_fallbacks = {"Nagar Nigam", "MPPB", "PWD", "Unknown"}
if derived_name not in generic_fallbacks:
authority_name = derived_name
clarify, clarify_q = needs_clarification(domain, signals, processed)
unit = IssueUnit(
set=domain,
subtype=subtype,
root_cause=generate_reason_text(domain, subtype, processed),
visible_symptom=f"User reported: {processed[:80]}",
public_private=public_private,
urgency=urgency,
confidence_band=confidence,
authority_type=authority_type,
authority_name=authority_name,
reasoning=(
f"Domain '{domain}', subtype '{subtype}' inferred from keywords. "
f"Ownership: {public_private}. "
f"Hazard signals: {signals.hazard_clues}. "
f"Legal signals: {signals.legal_clues}. "
f"Precedent applied: {has_precedent}."
),
clarification_needed=clarify,
clarification_question=clarify_q,
)
issue_units.append(unit)
# Fix 7: Priority sorting by urgency → hazard presence → public impact
has_hazard = bool(signals.hazard_clues)
def priority_key(i: int) -> Tuple[int, int, int]:
unit = issue_units[i]
u_score = urgency_rank.get(unit.urgency, 2)
# Hazard bumps priority up (lower = higher priority)
h_score = 0 if (has_hazard and unit.urgency == "high") else 1
# Public issues take priority over private
p_score = 0 if unit.public_private == "public" else 1
return (u_score, h_score, p_score)
sorted_indices = sorted(range(len(issue_units)), key=priority_key)
return Action(
issue_units=issue_units,
overall_priority_order=sorted_indices,
manual_review_recommended=any(u.confidence_band == "low" for u in issue_units),
insufficient_information=False,
disclaimer_needed=bool(signals.legal_clues),
)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203<!DOCTYPE html><html lang="en"><head> <link rel="icon" href="data:,"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Civic Grievance AI Portal</title> <!-- Use Inter font for a clean, formal look --> <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet"> <link rel="stylesheet" href="styles.css"></head><body> <!-- 1. Top Bar (Sanchar Saathi Style) --> <div class="top-bar"> <div class="tb-left"> <div class="tb-item"> <span class="hi">भारत सरकार</span> <span class="en">GOVERNMENT OF INDIA</span> </div> <div class="tb-item"> <span class="hi">प्रशासनिक सुधार मंत्रालय</span> <span class="en">MINISTRY OF PUBLIC GRIEVANCES</span> </div> </div> <div class="tb-right"> <span>SKIP TO MAIN CONTENT</span> <div class="tb-icons"> <span class="icon">🔍</span> <span class="icon">A</span> <span class="icon">A+</span> </div> </div> </div>
<!-- 2. Main Header --> <header class="main-header"> <div class="header-logo"> <div class="emblem-placeholder"> <div class="ashoka-chakra"></div> </div> <div class="header-titles"> <span class="hi">लोक शिकायत विभाग</span> <span class="en">DEPARTMENT OF PUBLIC GRIEVANCES</span> </div> </div> <div class="header-right-logos"> <div class="logo-box">Digital India</div> <div class="logo-box">Azadi Ka Amrit Mahotsav</div> </div> </header>
<!-- 3. Navigation Bar (Floating Button Tabs) --> <nav class="ss-nav"> <div class="nav-container"> <a href="#" class="home-btn"> <svg viewBox="0 0 24 24" width="22" height="22" stroke="currentColor" stroke-width="2" fill="none"><path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"></path><polyline points="9 22 9 12 15 12 15 22"></polyline></svg> </a> <div class="nav-links"> <a href="#" class="nav-btn">CITIZEN CENTRIC SERVICES</a> <a href="#" class="nav-btn">ABOUT</a> <a href="#" class="nav-btn">FILE COMPLAINT</a> <a href="#" class="nav-btn">FREQUENTLY ASKED QUESTIONS</a> <a href="#" class="nav-btn">MOBILE APP</a> </div> </div> </nav>
<!-- 4. Main Banner Wrapper (with Floating Cards) --> <div class="main-wrapper"> <div class="container"> <!-- Left Panel: Floating Minister Cards --> <aside class="left-floating-panel"> <div class="floating-card"> <img src="images/pm_modi.png" alt="Narendra Modi" class="card-img"> <div class="card-info"> <strong>Honorable Prime Minister</strong> <span>Shri Narendra Modi</span> </div> <div class="card-social"> <span>🐦</span> <span>🟦</span> <span>📸</span> </div> </div> <div class="floating-card"> <img src="images/mohan_yadav.png" alt="Mohan Yadav" class="card-img"> <div class="card-info"> <strong>Honnorable Chief Minister</strong> <span>Dr. Mohan Yadav</span> </div> <div class="card-social"> <span>🐦</span> <span>🟦</span> <span>📸</span> </div> </div> </aside>
<!-- Right Panel: Sanchar Saathi Integrated Banner --> <section class="banner-panel"> <div class="ss-banner"> <div class="ss-banner-header"> <h2>CIVIC GRIEVANCE AI PORTAL</h2> <p>AN INTEGRATED SPACE FOR CITIZEN CENTRIC SERVICES</p> </div> <div class="ss-banner-content"> <!-- Orange Info Blocks --> <div class="ss-orange-section"> <div class="orange-block"> <h3>REPORT</h3> <ul> <li>Civic Issues & Potholes</li> <li>Water Supply & Sanitation Delivery</li> <li>Unregistered Construction Work</li> <li>Electricity related issues</li> </ul> </div> <div class="orange-block"> <h3>TRACK</h3> <ul> <li>Your Registered Complaints</li> <li>Current Authority Status</li> <li>Expected Resolution Date</li> </ul> </div> </div>
<!-- Chatbot embedded seamlessly --> <div class="ss-chat-section"> <div class="chat-container"> <div class="chat-messages" id="chatMessages" aria-live="polite"> <div class="message bot"> <div class="message-content"> Welcome to the Civic Grievance AI Portal. Please choose one of the options if it matches your grievance or else write your own complaint. </div> </div> </div> <div class="typing-indicator hidden" id="typingIndicator" aria-hidden="true"> <span></span><span></span><span></span> </div> <div class="choice-panel" id="choicePanel">
<button class="choice-btn road-btn" data-example="There are large potholes on the road near my colony."> Civic Issues & Potholes </button>
<button class="choice-btn water-btn" data-example="No water supply in our area since morning."> Water Supply & Sanitation Delivery </button>
<button class="choice-btn illegal-btn" data-example="Illegal construction work is blocking the public path."> Unregistered Construction Work </button>
<button class="choice-btn electricity-btn" data-example="Electricity is not available for hours."> Electricity related issues </button>
<button class="choice-btn own-hover" id="writeOwnBtn"> Write my own complaint </button>
</div>
<!-- Chat Input (Hidden initially) --> <form class="chat-input-area hidden" id="chatForm"> <input type="text" id="chatInput" placeholder="Type your complaint here..." autocomplete="off" required> <button type="submit" id="sendBtn" aria-label="Send Message"> <svg viewBox="0 0 24 24" width="20" height="20" stroke="currentColor" stroke-width="2.5" fill="none" stroke-linecap="round" stroke-linejoin="round"> <line x1="22" y1="2" x2="11" y2="13"></line> <polygon points="22 2 15 22 11 13 2 9 22 2"></polygon> </svg> </button> </form> </div> </div> </div> <!-- Bottom Yellow Banner --> <div class="ss-banner-footer"> <div class="access-now">ACCESS NOW »</div> <div class="web-portal"> <span>Web Portal</span> <a href="#">https://civicai.gov.in</a> </div> </div> </div> </section> </div> </div>
<!-- Footer --> <footer class="main-footer"> <div class="footer-content"> <p>© Government of India – Civic AI System</p> </div> </footer> </body> <script src="app.js"></script></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446"""
inference.py — OpenEnv Inference Runner for Civic Grievance Decision System
Imports and uses environment.py. Do NOT run environment.py directly.
"""
from __future__ import annotations
from dotenv import load_dotenv
load_dotenv()
import json
import os
import sys
import traceback
from typing import Any, Dict, List, Optional
from openai import OpenAI
from environment import (
Action,
GrievanceEnvironment,
IssueUnit,
Observation,
TASKS,
)
# ---------------------------------------------------------------------------
# Configuration
# ---------------------------------------------------------------------------
API_BASE_URL: str = os.getenv("API_BASE_URL") or "https://router.huggingface.co/v1"
MODEL_NAME: str = os.getenv("MODEL_NAME") or "openai/gpt-oss-20b"
HF_TOKEN: str = os.getenv("HF_TOKEN") or os.getenv("API_KEY") or ""
if not HF_TOKEN:
print("[ERROR] No API key found. Set HF_TOKEN or API_KEY.")
sys.exit(1)
client = OpenAI(
api_key=HF_TOKEN,
base_url=API_BASE_URL,
)
BENCHMARK_NAME = "CivicGrievanceEnv"
# ---------------------------------------------------------------------------
# System Prompt
# ---------------------------------------------------------------------------
SYSTEM_PROMPT = """You are a civic grievance routing system for Indian municipalities.
RESPOND WITH VALID JSON ONLY. No explanation, no markdown, no preamble. Just JSON.
ROUTING RULES:
1. Safety > Public health > Disruption > Inconvenience
2. Root cause reasoning takes priority over surface wording
3. Public infrastructure -> government authority
4. Private property -> local_private_solution
5. Legal/ownership disputes -> guidance_only
6. Vague, abusive, or irrelevant input -> set insufficient_information=true, issue_units=[]
DOMAIN AUTHORITIES:
- sanitation:
drainage/nali/sewage -> Nagar nigam
water supply/paani -> Jal nigam
contamination/smell/dirty -> pradurshan niyantran board
private plumbing -> Licensed Plumber
- electricity:
outage/transformer/voltage -> MPEB/Bijli vibhag
billing/meter/overcharge -> Bijli vibhag — Billing Unit
theft/chor/illegal conn. -> Bijli vibhag — Vigilance/Enforcement
internal wiring/short circ. -> Qualified Electrician
- infrastructure:
road/sadak/pothole/bridge -> PWD
illegal construction -> Town planning department
legal dispute/encroachment -> town planning department / Legal Aid
URGENCY:
- high: fire, blast, death, toxic, electrocution, no water for days, emergency
- medium: frequent outage, blocked drain, days without service, disruption
- low: minor inconvenience, cosmetic issue, occasional problem
AUTHORITY_TYPE — use exactly one of:
government | local_private_solution | government_appeal | guidance_only | insufficient_information
CLARIFICATION — trigger only when:
- ownership is genuinely unclear (both public and private signals)
- domain collision with very weak signals
- root cause cannot be determined
- NOT based on complaint length alone
OUTPUT SCHEMA — follow exactly, do not add extra keys:
{
"issue_units": [
{
"set": "sanitation | electricity | infrastructure",
"subtype": "string",
"root_cause": "string",
"visible_symptom": "string",
"public_private": "public | private | disputed | unclear",
"urgency": "low | medium | high",
"confidence_band": "low | medium | high",
"authority_type": "government | local_private_solution | government_appeal | guidance_only | insufficient_information",
"authority_name": "string",
"reasoning": "string",
"clarification_needed": false,
"clarification_question": ""
}
],
"overall_priority_order": [0],
"manual_review_recommended": false,
"insufficient_information": false,
"disclaimer_needed": false
}
CONSTRAINTS:
- Maximum 4 issue_units
- clarification_question must be empty string "" when clarification_needed is false
- overall_priority_order is a 0-based index list into issue_units, sorted by priority
- Do not invent departments not listed above
- Do not hallucinate laws, case numbers, or FIR references
"""
# ---------------------------------------------------------------------------
# Fallback Action Dict
# ---------------------------------------------------------------------------
FALLBACK_ACTION_DICT: Dict[str, Any] = {
"issue_units": [],
"overall_priority_order": [],
"manual_review_recommended": True,
"insufficient_information": True,
"disclaimer_needed": False,
}
# ---------------------------------------------------------------------------
# Safe JSON Parsing
# ---------------------------------------------------------------------------
def safe_parse_json(raw: str) -> Dict[str, Any]:
"""
Attempt to parse raw LLM output as a JSON dict.
Returns FALLBACK_ACTION_DICT on any failure.
"""
if not raw:
return FALLBACK_ACTION_DICT
# Pass 1: direct parse
try:
result = json.loads(raw)
if isinstance(result, dict):
return result
except json.JSONDecodeError:
pass
# Pass 2: strip markdown code fences
cleaned = raw.strip()
if cleaned.startswith("```"):
lines = cleaned.splitlines()
lines = [ln for ln in lines if not ln.strip().startswith("```")]
cleaned = "\n".join(lines).strip()
try:
result = json.loads(cleaned)
if isinstance(result, dict):
return result
except json.JSONDecodeError:
pass
# Pass 3: extract first { ... } substring
start = cleaned.find("{")
end = cleaned.rfind("}")
if start != -1 and end != -1 and end > start:
try:
result = json.loads(cleaned[start:end + 1])
if isinstance(result, dict):
return result
except json.JSONDecodeError:
pass
return FALLBACK_ACTION_DICT
# ---------------------------------------------------------------------------
# Build Action from Parsed Dict
# ---------------------------------------------------------------------------
def build_action_from_dict(data: Dict[str, Any]) -> Optional[Action]:
"""
Construct an Action Pydantic model from a parsed dict.
Returns None if construction fails.
"""
raw_units = data.get("issue_units", [])
if not isinstance(raw_units, list):
return None
issue_units: List[IssueUnit] = []
for ru in raw_units[:4]:
if not isinstance(ru, dict):
continue
try:
unit = IssueUnit(
set=str(ru.get("set", "sanitation")),
subtype=str(ru.get("subtype", "unknown")),
root_cause=str(ru.get("root_cause", "")),
visible_symptom=str(ru.get("visible_symptom", "")),
public_private=str(ru.get("public_private", "unclear")),
urgency=str(ru.get("urgency", "low")),
confidence_band=str(ru.get("confidence_band", "low")),
authority_type=str(ru.get("authority_type", "insufficient_information")),
authority_name=str(ru.get("authority_name", "Unknown")),
reasoning=str(ru.get("reasoning", "")),
clarification_needed=bool(ru.get("clarification_needed", False)),
clarification_question=str(ru.get("clarification_question", "")),
)
issue_units.append(unit)
except Exception:
continue
priority_order = data.get("overall_priority_order", list(range(len(issue_units))))
if not isinstance(priority_order, list):
priority_order = list(range(len(issue_units)))
try:
return Action(
issue_units=issue_units,
overall_priority_order=priority_order,
manual_review_recommended=bool(data.get("manual_review_recommended", False)),
insufficient_information=bool(data.get("insufficient_information", False)),
disclaimer_needed=bool(data.get("disclaimer_needed", False)),
)
except Exception:
return None
# ---------------------------------------------------------------------------
# LLM Call
# ---------------------------------------------------------------------------
def call_llm(observation: Observation) -> str:
"""
Send the observation to the LLM and return raw response string.
Raises on API failure — caller handles fallback.
"""
user_message = (
f"COMPLAINT:\n{observation.raw_text}\n\n"
f"PROCESSED TEXT:\n{observation.processed_text}\n\n"
f"DETECTED DOMAINS: {observation.possible_sets}\n"
f"KEYWORDS: {observation.extracted_signals.keywords}\n"
f"HAZARD CLUES: {observation.extracted_signals.hazard_clues}\n"
f"OWNERSHIP CLUES: {observation.extracted_signals.ownership_clues}\n"
f"LEGAL CLUES: {observation.extracted_signals.legal_clues}\n"
f"RULE-BASED URGENCY: {observation.extracted_signals.urgency_level}\n"
f"LOCATION: {observation.location}\n\n"
f"SIMILAR PAST CASES:\n"
f"{json.dumps(observation.memory_hits, ensure_ascii=False, indent=2)}\n\n"
"Produce a structured JSON decision following the schema exactly."
)
completion = client.chat.completions.create(
model=MODEL_NAME,
temperature=0.0,
max_tokens=2000,
messages=[
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": user_message},
],
)
content = completion.choices[0].message.content
raw = content.strip() if content else ""
return raw
# ---------------------------------------------------------------------------
# Output Formatting
# ---------------------------------------------------------------------------
def fmt_bool(value: bool) -> str:
return "true" if value else "false"
def fmt_action_summary(action: Action) -> str:
return f"issues:{len(action.issue_units)}|priority:{action.overall_priority_order}"
def print_start(task_id: str) -> None:
print(f"[START] task={task_id} env={BENCHMARK_NAME} model={MODEL_NAME}")
def print_step(
step: int,
action: Action,
reward: float,
done: bool,
error: Optional[str],
) -> None:
action_str = fmt_action_summary(action)
error_str = error if error else "null"
print(
f"[STEP] step={step} action={action_str} "
f"reward={reward:.2f} done={fmt_bool(done)} error={error_str}"
)
def print_end(success: bool, steps: int, score: float, rewards: List[float]) -> None:
rewards_str = ",".join(f"{r:.2f}" for r in rewards)
print(
f"[END] success={fmt_bool(success)} steps={steps} "
f"score={score:.2f} rewards={rewards_str}"
)
def print_routing_detail(action: Action, reward_score: float, feedback: str) -> None:
"""Human-readable routing decision block printed between STEP and END."""
print()
print("=" * 60)
print("ROUTING DECISION")
print("=" * 60)
flags = []
if action.insufficient_information:
flags.append("INSUFFICIENT INFORMATION")
if action.manual_review_recommended:
flags.append("MANUAL REVIEW RECOMMENDED")
if action.disclaimer_needed:
flags.append("LEGAL DISCLAIMER APPLIES")
if flags:
for f in flags:
print(f" >> {f}")
print()
if not action.issue_units:
print(" No issue units routed.")
else:
for i, unit in enumerate(action.issue_units):
print(f" Issue {i + 1}: [{unit.set.upper()}] {unit.subtype}")
print(f" Urgency : {unit.urgency}")
print(f" Ownership : {unit.public_private}")
print(f" Authority : {unit.authority_name} ({unit.authority_type})")
print(f" Confidence : {unit.confidence_band}")
print(f" Root cause : {unit.root_cause}")
if unit.clarification_needed:
print(f" Clarify? : {unit.clarification_question}")
print()
if action.overall_priority_order:
print(f" Priority order : {action.overall_priority_order}")
print()
print(f" Reward : {reward_score:.2f} | {feedback}")
print("=" * 60)
print()
# ---------------------------------------------------------------------------
# Main Flow
# ---------------------------------------------------------------------------
def main() -> None:
rewards: List[float] = []
step_count = 0
score = 0.0
success = False
task_id: Optional[str] = None
action: Optional[Action] = None
error_msg: Optional[str] = None
observation: Optional[Observation] = None
try:
# ── Gather inputs ────────────────────────────────────────────────────
print()
complaint = input("Enter complaint text: ").strip()
if not complaint:
print("No complaint provided. Exiting.")
sys.exit(0)
task_input = input(
"Task ID for evaluation [easy / medium / hard] or Enter to skip: "
).strip()
task_id = task_input if task_input in TASKS else None
# ── Initialise environment ───────────────────────────────────────────
env = GrievanceEnvironment()
observation = env.reset(complaint, task_id=task_id)
print_start(task_id or "custom")
# ── Call LLM ─────────────────────────────────────────────────────────
raw_llm = ""
try:
raw_llm = call_llm(observation)
except Exception as exc:
error_msg = f"LLM error: {type(exc).__name__}"
print(f" [WARNING] {error_msg} — falling back to rule-based action.")
# ── Parse and build Action ────────────────────────────────────────────
if raw_llm:
parsed = safe_parse_json(raw_llm)
action = build_action_from_dict(parsed)
if action is None and error_msg is None:
error_msg = "LLM parse failed — used rule-based fallback"
if action is None:
action = GrievanceEnvironment.build_rule_based_action(observation)
# Clarification loop
for unit in action.issue_units:
if unit.clarification_needed and unit.clarification_question.strip():
print()
print("[CLARIFICATION NEEDED]")
print(unit.clarification_question)
user_reply = input("Reply: ").strip()
print()
updated_text = observation.raw_text + " " + user_reply
observation = env.reset(updated_text, task_id=task_id or None)
action = GrievanceEnvironment.build_rule_based_action(observation)
break
# ── Step environment ─────────────────────────────────────────────────
_, reward_result, done, info = env.step(action)
step_count = info.get("step_count", 1)
score = reward_result.score
rewards.append(score)
# ── Output ────────────────────────────────────────────────────────────
print_step(step_count, action, score, done, error_msg)
print_routing_detail(action, reward_result.score, reward_result.feedback)
success = True
except KeyboardInterrupt:
print("\n[Interrupted]")
error_msg = "interrupted"
except Exception as exc:
error_msg = f"{type(exc).__name__}: {exc}"
print(f"\n[ERROR] {error_msg}")
traceback.print_exc()
finally:
# Always emit [END]
print_end(success, step_count, score, rewards)
if __name__ == "__main__":
main()
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254# OpenEnv Specification — Civic Grievance Decision Environment
# Version: 1.0
name: CivicGrievanceEnv
version: "1.0"
description: >
AI-powered grievance routing and decision-support environment for Indian municipalities.
Accepts messy real-world complaints covering sanitation, electricity, and infrastructure.
Applies rule-based reasoning augmented by LLM assistance to produce structured routing
decisions with deterministic reward evaluation.
# ---------------------------------------------------------------------------
# Entry Points
# ---------------------------------------------------------------------------
entry_points:
environment: environment.py
inference: inference.py
environment_class: GrievanceEnvironment
inference_main: "python inference.py"
# ---------------------------------------------------------------------------
# Metadata
# ---------------------------------------------------------------------------
metadata:
domain: civic_grievance
language: ["en", "hi"]
geography: India
step_type: single_step
evaluation_mode: deterministic
multi_issue: true
max_issue_units: 4
# ---------------------------------------------------------------------------
# Interface
# ---------------------------------------------------------------------------
interface:
methods:
reset:
signature: "reset(complaint: str, task_id: Optional[str]) -> Observation"
step:
signature: "step(action: Action) -> (Observation, RewardResult, bool, dict)"
state:
signature: "state() -> dict"
build_rule_based_action:
signature: "build_rule_based_action(observation: Observation) -> Action"
observation_fields:
raw_text: string
processed_text: string
possible_sets:
type: list
values: [sanitation, electricity, infrastructure]
extracted_signals:
keywords: list
hazard_clues: list
ownership_clues: list
domain_clues: list
urgency_level: ["low", "medium", "high"]
scale_clues: list
legal_clues: list
location:
type: string
required: false
image_tags:
type: list
required: false
memory_hits:
type: list
# ---------------------------------------------------------------------------
# Action Schema
# ---------------------------------------------------------------------------
action_fields:
issue_units:
type: list
max_items: 4
item_fields:
set: [sanitation, electricity, infrastructure]
subtype: string
root_cause: string
visible_symptom: string
public_private: [public, private, disputed, unclear]
urgency: [low, medium, high]
confidence_band: [low, medium, high]
authority_type:
- government
- local_private_solution
- government_appeal
- guidance_only
- insufficient_information
authority_name: string
reasoning: string
clarification_needed: boolean
clarification_question: string
overall_priority_order: list
manual_review_recommended: boolean
insufficient_information: boolean
disclaimer_needed: boolean
# ---------------------------------------------------------------------------
# Reward Rules
# ---------------------------------------------------------------------------
reward:
type: discrete
possible_values: [0.0, 0.3, 0.5, 1.0]
rules:
- condition: "correct set AND correct authority_type"
score: 1.0
- condition: "correct set BUT wrong authority_type"
score: 0.5
- condition: "insufficient_information OR manual_review"
score: 0.3
- condition: "incorrect routing"
score: 0.0
# ---------------------------------------------------------------------------
# Tasks
# ---------------------------------------------------------------------------
tasks:
easy:
id: easy_001
difficulty: easy
complaint: >
The street drain near ward 5 is completely blocked and overflowing.
expected_output:
set: sanitation
subtype: drainage_blockage
authority_type: government
authority_name: "Municipal Corporation"
urgency: medium
public_private: public
medium:
id: medium_001
difficulty: medium
complaint: >
Electricity has been cut for 2 days and the drain in front is overflowing.
expected_output:
sets: [electricity, sanitation]
authority_names: ["MPPB", "Municipal Corporation"]
urgency: medium
hard:
id: hard_001
difficulty: hard
complaint: >
Illegal construction on a public pathway and municipality is not responding.
expected_output:
set: infrastructure
subtype: illegal_construction
authority_type: guidance_only
public_private: disputed
# ---------------------------------------------------------------------------
# Domain Routing Map
# ---------------------------------------------------------------------------
domain_routing:
sanitation:
subtypes:
- drainage_blockage
- sewage_overflow
- garbage_collection
- water_supply
- water_contamination
authorities:
public: "Municipal Corporation"
water_supply: "Water Supply Department"
contamination: "Pollution Control Board"
private: "Licensed Plumber"
electricity:
subtypes:
- power_outage
- transformer_fault
- voltage_fluctuation
- billing_dispute
- electricity_theft
- internal_wiring
authorities:
outage: "MPPB"
billing: "MPPB Billing Unit"
theft: "MPPB Enforcement"
private: "Qualified Electrician"
infrastructure:
subtypes:
- road_damage
- bridge_damage
- footpath_obstruction
- illegal_construction
authorities:
road: "Public Works Department (PWD)"
illegal: "Town Planning Department"
legal: "Legal Aid / Town Planning"
# ---------------------------------------------------------------------------
# Design Notes
# ---------------------------------------------------------------------------
design_notes:
pipeline: >
preprocessing → signal extraction → domain detection →
issue generation → deduplication → precedent matching →
routing → reward
multi_issue: >
Supports up to 4 issue units.
clarification: >
Triggered only on ambiguity.
guidance: >
System assists routing, not legal resolution.
# ---------------------------------------------------------------------------
# Dependencies
# ---------------------------------------------------------------------------
dependencies:
python: ">=3.9"
pydantic: ">=2.0.0"
openai: ">=1.0.0"12345flask
flask-cors
openai
pydantic
python-dotenv123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap');
:root { /* Sanchar Saathi Specific Colors */ --ss-nav-bg: #84B9FA; --ss-nav-btn: #B3D8FA; --ss-nav-btn-hover: #D6E9FD; --ss-nav-text: #052654; --ss-home-bg: #14499E; --ss-blue-banner: #0077D3; --ss-orange: #EC8624; --ss-yellow: #FED40E; --color-white: #FFFFFF; --color-text: #1E293B; --color-gray-text: #475569; --color-border: #E2E8F0;
--shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.1); --shadow-floating: 0 10px 20px rgba(0,0,0,0.12);}
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: 'Inter', Arial, sans-serif; color: var(--color-text); display: flex; flex-direction: column; min-height: 100vh; background-color: white;}
/* 1. Top Bar */.top-bar { display: flex; justify-content: space-between; padding: 0.5rem 5%; font-size: 0.75rem; border-bottom: 1px solid #E2E8F0; background-color: #FAFAFA;}
.tb-left { display: flex; gap: 2rem; }.tb-item { display: flex; flex-direction: column; }.tb-item .hi { font-weight: 700; color: #1E293B; }.tb-item .en { color: #64748B; font-weight: 500; letter-spacing: 0.02em; }
.tb-right { display: flex; align-items: center; gap: 1.5rem; font-weight: 600; color: #475569;}.tb-icons { display: flex; gap: 0.75rem;}.icon { font-weight: bold; cursor: pointer;}
/* 2. Main Header */.main-header { display: flex; justify-content: space-between; align-items: center; padding: 1rem 5%; background-color: var(--color-white);}
.header-logo { display: flex; align-items: center; gap: 1rem;}
.emblem-placeholder { width: 52px; height: 52px; border-radius: 50%; border: 2px solid #334155; position: relative; display: flex; justify-content: center; align-items: center;}
.ashoka-chakra { width: 38px; height: 38px; border-radius: 50%; border: 1px solid #334155; background: repeating-conic-gradient(from 0deg, #334155 0deg 2deg, transparent 2deg 15deg);}
.header-titles { display: flex; flex-direction: column;}.header-titles .hi { font-weight: 800; font-size: 1.25rem; color: #0F172A;}.header-titles .en { font-weight: 600; font-size: 0.85rem; color: #334155; letter-spacing: 0.02em;}
.header-right-logos { display: flex; gap: 1rem;}.logo-box { padding: 0.5rem 1rem; background: #F8FAFC; border: 1px solid #E2E8F0; border-radius: 4px; font-weight: 700; color: #475569; font-size: 0.8rem; display: flex; align-items: center;}
/* 3. Navigation Bar (Floating Pills) */.ss-nav { background-color: var(--ss-nav-bg); padding: 0 5%; display: flex; align-items: center; border-bottom: 2px solid #5798E9;}
.nav-container { display: flex; align-items: stretch; height: 54px; width: 100%;}
.home-btn { background-color: var(--ss-home-bg); color: white; width: 54px; display: flex; align-items: center; justify-content: center; border-radius: 8px 8px 0 0; margin-top: 6px;}
.nav-links { display: flex; align-items: flex-end; gap: 4px; margin-left: 10px; height: 100%;}
.nav-btn { background-color: var(--ss-nav-btn); color: var(--ss-nav-text); text-decoration: none; font-weight: 700; font-size: 0.8rem; padding: 0.75rem 1.25rem; border-radius: 6px 6px 0 0; transition: all 0.2s; text-transform: uppercase; letter-spacing: 0.02em; box-shadow: 0 -2px 5px rgba(0,0,0,0.05); /* Soft shadow indicating floating tab */}
.nav-btn:hover { background-color: var(--ss-nav-btn-hover); transform: translateY(-2px);}
/* 4. Main Wrapper Layout */.main-wrapper { flex: 1; /* Soft techy light blue background resembling Sanchar Saathi */ background: linear-gradient(135deg, #E0F2FE 0%, #BAE6FD 100%); padding: 2.5rem 5%;}
.container { max-width: 1400px; margin: 0 auto; display: flex; gap: 2rem; align-items: flex-start;}
/* 5. Left Floating Panel (Minister Cards) */.left-floating-panel { width: 250px; display: flex; flex-direction: column; gap: 1.5rem;}
.floating-card { background: white; border-radius: 6px; box-shadow: var(--shadow-floating); overflow: hidden; display: flex; flex-direction: column; align-items: center; border: 1px solid rgba(255,255,255,0.5); transition: transform 0.2s;}
.floating-card:hover { transform: translateY(-5px);}
.card-img-placeholder { width: 100%; height: 150px; background: linear-gradient(to bottom, #F1F5F9, #E2E8F0); display: flex; justify-content: center; align-items: center;}
.card-img { width: 100%; height: 170px; object-fit: cover; object-position: top; background: #F1F5F9;}
.card-info { padding: 1rem; text-align: center; background: #EFF6FF; width: 100%;}
.card-info strong { display: block; color: #0F172A; font-size: 0.9rem; font-weight: 800; margin-bottom: 0.25rem;}
.card-info span { font-size: 0.8rem; color: #475569; font-weight: 500;}
.card-social { display: flex; gap: 1rem; padding: 0.75rem; background: white; width: 100%; justify-content: center; border-top: 1px solid #E2E8F0; font-size: 1.1rem; cursor: pointer;}
/* 6. Banner Panel (Right Area) */.banner-panel { flex: 1;}
.ss-banner { background-color: var(--ss-blue-banner); border-radius: 12px; overflow: hidden; box-shadow: var(--shadow-floating); display: flex; flex-direction: column; position: relative; border: 3px solid #60A5FA; /* Nice border to make it pop */}
.ss-banner-header { text-align: center; padding: 1.5rem; color: white; background: linear-gradient(rgba(0,0,0,0), rgba(0,0,0,0.1));}
.ss-banner-header h2 { font-size: 2.4rem; font-weight: 800; margin-bottom: 0.25rem; letter-spacing: 1px; text-shadow: 1px 2px 4px rgba(0,0,0,0.2);}
.ss-banner-header p { font-size: 1.1rem; font-weight: 600; letter-spacing: 1.5px; color: #DBEAFE;}
.ss-banner-content { display: flex; padding: 0 1.5rem 1.5rem 1.5rem; gap: 1.5rem;}
/* Orange Option Blocks */.ss-orange-section { flex: 0.8; display: flex; flex-direction: column; gap: 1rem;}
.orange-block { background-color: var(--ss-orange); color: white; padding: 1.5rem; border-radius: 8px; box-shadow: inset 0 0 20px rgba(0,0,0,0.05);}
.orange-block h3 { font-size: 1.8rem; font-weight: 800; margin-bottom: 1rem; border-left: 5px solid white; padding-left: 12px; text-shadow: 1px 1px 2px rgba(0,0,0,0.1);}
.orange-block ul { list-style: none;}
.orange-block ul li { font-size: 0.95rem; font-weight: 600; margin-bottom: 0.6rem; display: flex; align-items: center;}
.orange-block ul li::before { content: '▶'; font-size: 0.7rem; margin-right: 8px; color: #FFEFE1;}
/* Chat UI Overwrite */.ss-chat-section { flex: 1.2;}
.chat-container { background: var(--color-white); border-radius: 10px; display: flex; flex-direction: column; height: 480px; overflow: hidden; box-shadow: 0 10px 25px rgba(0,0,0,0.15);}
.chat-messages { flex: 1; padding: 1.25rem; overflow-y: auto; display: flex; flex-direction: column; gap: 1rem; background-color: #F8FAFC;}
.message { display: flex; width: 100%; animation: fadeIn 0.3s ease;}
@keyframes fadeIn { from { opacity: 0; transform: translateY(5px); } to { opacity: 1; transform: translateY(0); }}
.message.user { justify-content: flex-end; }.message.bot { justify-content: flex-start; }
.message-content { max-width: 90%; padding: 0.85rem 1.1rem; font-size: 0.95rem; line-height: 1.5; border-radius: 12px;}
.message.user .message-content { background-color: #ECFCCB; /* Lime light green */ color: #3F6212; border-bottom-right-radius: 0; border: 1px solid #D9F99D;}
.message.bot .message-content { background-color: white; color: var(--color-text); border-bottom-left-radius: 0; border: 1px solid var(--color-border); box-shadow: var(--shadow-md);}
/* Chat Input */.chat-input-area { padding: 1rem; background-color: white; border-top: 1px solid var(--color-border); display: flex; gap: 0.75rem;}
#chatInput { flex: 1; padding: 0.75rem 1.25rem; border: 1px solid var(--color-border); border-radius: 30px; font-size: 0.95rem; outline: none; transition: all 0.2s;}
#chatInput:focus { border-color: var(--ss-blue-banner); box-shadow: 0 0 0 3px rgba(0, 119, 211, 0.1);}
#sendBtn { background-color: var(--ss-orange); color: white; border: none; width: 46px; height: 46px; border-radius: 50%; display: flex; align-items: center; justify-content: center; cursor: pointer; transition: transform 0.1s, background-color 0.2s;}#sendBtn:hover { background-color: #D3741C; }#sendBtn:active { transform: scale(0.95); }
/* Banner Footer */.ss-banner-footer { display: flex; background-color: white; align-items: stretch; border-top: 1px solid #E2E8F0;}
.access-now { background-color: var(--ss-yellow); color: #0F172A; font-weight: 800; font-size: 1.4rem; padding: 1rem 2.5rem; display: flex; align-items: center; text-transform: uppercase;}
.web-portal { padding: 1rem 2.5rem; display: flex; flex-direction: column; justify-content: center;}
.web-portal span { color: var(--ss-blue-banner); font-weight: 800; font-size: 0.85rem; text-transform: uppercase;}
.web-portal a { color: var(--ss-orange); font-size: 1.25rem; font-weight: 700; text-decoration: none;}
/* Chat Result Cards Formatting */.result-card { background: #F8FAFC; border: 1px solid #CBD5E1; border-radius: 8px; padding: 1rem; margin-top: 0.75rem;}.result-header { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 0.75rem;}.result-title { font-weight: 800; font-size: 1rem; color: #1E293B; }.tag { font-size: 0.7rem; font-weight: 800; text-transform: uppercase; padding: 0.25rem 0.5rem; border-radius: 4px;}.tag.high { background-color: #FEE2E2; color: #B91C1C; border: 1px solid #FECACA; }.tag.medium { background-color: #FEF3C7; color: #B45309; border: 1px solid #FDE68A; }.tag.low { background-color: #ECFCCB; color: #4D7C0F; border: 1px solid #D9F99D; }
.authority-highlight { background-color: #E0E7FF; color: #3730A3; padding: 0.35rem 0.6rem; border-radius: 6px; font-weight: 700; font-size: 0.85rem; display: inline-block; margin-bottom: 0.75rem; border-left: 4px solid #4F46E5;}.reason-text { font-size: 0.9rem; color: var(--color-gray-text); margin-bottom: 0.75rem; }
.recommendation-box { background-color: #FFFFFF; border: 1px solid #E2E8F0; border-left: 4px solid var(--ss-orange); padding: 0.75rem; font-size: 0.9rem; border-radius: 4px;}.recommendation-box strong { color: #0F172A; display: block; margin-bottom: 0.25rem; font-weight: 700; }
/* Typing indicator */.typing-indicator { padding: 0.5rem 1rem; display: flex; gap: 4px;}.typing-indicator.hidden { display: none!important; }.typing-indicator span { width: 7px; height: 7px; background-color: #64748B; border-radius: 50%; animation: bounce 1.4s infinite ease-in-out both;}.typing-indicator span:nth-child(1) { animation-delay: -0.32s; }.typing-indicator span:nth-child(2) { animation-delay: -0.16s; }
/* Footer */.main-footer { background-color: #0F172A; color: #94A3B8; text-align: center; padding: 2rem; font-size: 0.9rem; font-weight: 600;}
/* Responsive adjustments */@media (max-width: 1024px) { .container { flex-direction: column; } .left-floating-panel { width: 100%; flex-direction: row; justify-content: center; } .ss-banner-content { flex-direction: column; }}.choice-panel { display: flex; flex-direction: column; gap: 14px; margin-top: 20px;}.choice-btn { display: block; width: 100%; padding: 16px 18px; border: 1px solid #e2e8f0; border-radius: 12px; background: #ffffff; color: #0f172a; font-weight: 600; font-size: 15px; text-align: left; cursor: pointer; box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08); transition: all 0.2s ease;}.choice-btn:hover { background: #f8fafc; transform: translateX(6px); box-shadow: 0 8px 20px rgba(0, 0, 0, 0.12);}.electricity-btn { border-left: 5px solid #f59e0b; background: #fffaf0;}
.electricity-btn:hover { background: #fff7ed; transform: translateX(6px); box-shadow: 0 8px 20px rgba(0, 0, 0, 0.12);}.road-btn { border-left: 5px solid #f59e0b; background: #fffaf0;}
.road-btn:hover { background: #fff7ed; transform: translateX(6px); box-shadow: 0 8px 20px rgba(0, 0, 0, 0.12);}.water-btn { border-left: 5px solid #f59e0b; background: #fffaf0;}
.water-btn:hover { background: #fff7ed; transform: translateX(6px); box-shadow: 0 8px 20px rgba(0, 0, 0, 0.12);}.illegal-btn { border-left: 5px solid #f59e0b; background: #fffaf0;}
.illegal-btn:hover { background: #fff7ed; transform: translateX(6px); box-shadow: 0 8px 20px rgba(0, 0, 0, 0.12);}.own-btn { border-left: 5px solid #f59e0b; background: #fffaf0;}
.own-btn:hover { background: #fff7ed; transform: translateX(6px); box-shadow: 0 8px 20px rgba(0, 0, 0, 0.12);}.hidden { display: none!important; }.gitattributes+2-35
.gitignoreAdded+14
DockerfileAdded+22
README.md+169-11
app.jsAdded+211
app.pyAdded+449
environment.pyAdded+1050
index.htmlAdded+203
inference.pyAdded+446
openenv.yamlAdded+254
requirements.txtAdded+5
styles.cssAdded+639