Spaces:
Sleeping
Sleeping
Upload main.py
Browse files7 unmodified lines89101112131495 unmodified lines110111112113114115116117118119120116121122123124234 unmodified lines35936036136236336436536636736836936337037137237337436 unmodified lines41141241340641441541627 unmodified lines4444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275287 unmodified lines53653753853954054154254354454554654754854955055113 unmodified lines56556656756856957057157257357457547257657757857990 unmodified lines67067167267367467567626 unmodified lines7037047056016026036046056066077067077087097107117127132 unmodified lines7167177187197207217222 unmodified lines7257267277287297307317328 unmodified lines74174274374474574674774874975075164464564675275375475575675775875976076176276376476510 unmodified lines7767777787797807817827837847857867877887897907917927937947 unmodified linesfrom email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipartfrom typing import List, Optionalimport requests
from fastapi import FastAPI, Request, Form, UploadFile, File, WebSocket, WebSocketDisconnect, BackgroundTasksfrom fastapi.middleware.cors import CORSMiddleware95 unmodified lines# Mount static folder for downloads and uploadsapp.mount("/static", StaticFiles(directory="static"), name="static")
from analytics_db import init_db, log_session, log_utterance, get_analytics_data, get_session_timeline, get_articles_by_emotion# Initialize local SQLite analytics databaseinit_db()
# Initialize Templatestemplates = Jinja2Templates(directory="templates")
# Target model ID for Multimodal Live APIMODEL_ID = "gemini-3.1-flash-live-preview"MODEL_ID = "gemini-3.8-live"
def extract_text_from_docx(file_path: str) -> str: """Extracts raw text from a Microsoft Word document (.docx)."""234 unmodified lines if grounding == "true" and grounding_instructions.strip(): system_instruction += f"\n\nSTRICT GROUNDING & CONTEXT BOUNDING RULES:\n{grounding_instructions}"
article_filename = f"tron_article_{uuid.uuid4().hex}.html"
# Dynamic JSON config to embed inside downloaded file tron_config = { "voice": voice, "system_instruction": system_instruction, "greeting": greeting, "document_context": document_context, "silence_duration_ms": silence_duration_ms "silence_duration_ms": silence_duration_ms, "article_id": article_filename.split(".html")[0] }
# Determine backend URL: use custom_backend_url if provided, otherwise derive it dynamically36 unmodified lines html_content = template_response.body.decode("utf-8") # Save the compiled HTML file permanently under static/articles/ article_filename = f"tron_article_{uuid.uuid4().hex}.html" article_path = os.path.join("static", "articles", article_filename) with open(article_path, "w", encoding="utf-8") as f: f.write(html_content)27 unmodified lines "filename": article_filename }
# ANALYTICS DASHBOARD PORTAL & API ENDPOINTS
@app.get("/admin/analytics", response_class=HTMLResponse)async def admin_analytics_page(request: Request): return templates.TemplateResponse(request=request, name="admin_analytics.html")
@app.get("/api/analytics/data")async def api_analytics_data(): return get_analytics_data()
@app.get("/api/analytics/timeline/{session_id}")async def api_session_timeline(session_id: str): return get_session_timeline(session_id)
@app.get("/api/analytics/emotion/{emotion}")async def api_articles_by_emotion(emotion: str): return get_articles_by_emotion(emotion)
def get_geoip_location(ip: str): """Retrieves country and city from client IP using a free API.""" try: if not ip or ip in ["127.0.0.1", "localhost", "testclient", "::1"]: return "India", "Local Dev" # Strip proxies/multiple IPs real_ip = ip.split(",")[0].strip() r = requests.get(f"http://ip-api.com/json/{real_ip}", timeout=1.5) if r.status_code == 200: res = r.json() if res.get("status") == "success": return res.get("country", "India"), res.get("city", "Unknown") except Exception as e: print(f"[WARNING] Geo-IP lookup failed for {ip}: {e}", flush=True) return "India", "Unknown"
async def analyze_and_log_sentiment(session_id: str, user_text: str, model_text: str, api_key: str): """Asynchronously calls Gemini text API to analyze user sentiment and logs it to SQLite.""" try: if not user_text.strip(): return prompt = ( f"Analyze the sentiment and emotional state of this user utterance: \"{user_text}\"\n" f"Context: The user is interacting with an AI news/education assistant.\n\n" f"Respond with a JSON object containing:\n" f"- primary_emotion: Choose exactly one of these categories: [admiration, amusement, anger, annoyance, approval, caring, confusion, curiosity, desire, disappointment, disapproval, disgust, embarrassment, excitement, fear, gratitude, grief, joy, love, nervousness, optimism, pride, realization, relief, remorse, sadness, surprise, neutral].\n" f"- secondary_emotion: Choose one category from the same list (or 'neutral').\n" f"- valence: Float value between -1.0 (very negative) and +1.0 (very positive).\n" f"- arousal: Float value between -1.0 (very calm/sleepy) and +1.0 (very active/agitated/energetic).\n" f"- dominance: Float value between -1.0 (submissive/helpless) and +1.0 (empowered/dominant/in control)." ) # Call Gemini Text API asynchronously in the background loop = asyncio.get_event_loop() def run_call(): c = genai.Client(api_key=api_key) resp = c.models.generate_content( model="gemini-2.5-flash", contents=prompt, config=types.GenerateContentConfig( response_mime_type="application/json", ) ) return resp.text resp_text = await loop.run_in_executor(None, run_call) res = json.loads(resp_text) primary = res.get("primary_emotion", "neutral") secondary = res.get("secondary_emotion", "neutral") valence = float(res.get("valence", 0.0)) arousal = float(res.get("arousal", 0.0)) dominance = float(res.get("dominance", 0.0)) log_utterance(session_id, user_text, model_text, primary, secondary, valence, arousal, dominance) print(f"[DEBUG] Logged sentiment for {session_id}: {primary} (Valence: {valence})", flush=True) except Exception as e: print(f"[ERROR] Sentiment analysis background task failed: {e}", flush=True)
# WEBSOCKET BI-DIRECTIONAL BRIDGE
@app.websocket("/ws/live")7 unmodified lines await websocket.close(code=1008, reason="GEMINI_API_KEY not configured in .env file.") return
# Extract query params for session RAG tracking query_params = websocket.query_params article_id = query_params.get("article_id", "general") session_id = query_params.get("session_id", "") if not session_id: session_id = f"session_{uuid.uuid4().hex[:12]}"
current_user_text = "" current_model_text = ""
# Wait for the client to send the setup configuration try: setup_data = await websocket.receive_text()13 unmodified lines document_context = config_payload.get("document_context", "") silence_duration_ms = config_payload.get("silence_duration_ms", 1000)
# Log session connection metadata and geo location client_ip = websocket.client.host forwarded_for = websocket.headers.get("x-forwarded-for") if forwarded_for: client_ip = forwarded_for.split(",")[0].strip() country, city = get_geoip_location(client_ip) log_session(session_id, article_id, voice_name, country, city)
print(f"[DEBUG] Received setup config. Voice: {voice_name}, Instruction length: {len(system_instruction)}, Context length: {len(document_context)}, VAD Silence: {silence_duration_ms}ms", flush=True) print(f"[DEBUG] Received setup config. Session: {session_id}, Voice: {voice_name}, Instruction length: {len(system_instruction)}, Context length: {len(document_context)}, VAD Silence: {silence_duration_ms}ms", flush=True)
client = genai.Client(api_key=api_key) state = {"in_tool_call": False}90 unmodified lines # Bidirectional forwarding loops async def receive_from_client(): """Loop: Receive 16kHz PCM audio bytes from browser and forward to Gemini Live session.""" nonlocal current_user_text try: while True: data = await websocket.receive()26 unmodified lines print(f"[DEBUG] Received text message from client: {data['text']}", flush=True) msg = json.loads(data["text"]) if msg.get("type") == "input_text": await session.send_client_content( turns=types.Content( role="user", parts=[types.Part(text=msg["text"])] ), turn_complete=True ) current_user_text = msg.get("text", "") await session.send_realtime_input(text=msg["text"]) elif msg.get("type") == "audio_stream_end": print("[DEBUG] Client detected end-of-speech (Hybrid VAD). Sending audio_stream_end.", flush=True) await session.send_realtime_input(audio_stream_end=True) except WebSocketDisconnect: raise except Exception as e:2 unmodified lines
async def send_to_client(): """Loop: Receive responses/tool calls from Gemini Live session and forward/process them.""" nonlocal current_user_text, current_model_text try: while True: async for response in session.receive():2 unmodified lines # Forward transcription events if getattr(response.server_content, "input_transcription", None) is not None: t = response.server_content.input_transcription if t.text: current_user_text = t.text await websocket.send_json({ "type": "input_transcription", "text": t.text,8 unmodified lines }) if getattr(response.server_content, "output_transcription", None) is not None: t = response.server_content.output_transcription if t.text: current_model_text = t.text await websocket.send_json({ "type": "output_transcription", "text": t.text, "finished": getattr(t, "finished", False) })
# Let client know model is actively speaking await websocket.send_json({"type": "model_speaking", "speaking": True})
model_turn = response.server_content.model_turn if model_turn is not None: for part in model_turn.parts: if part.inline_data is not None: # Let client know model is actively speaking audio await websocket.send_json({"type": "model_speaking", "speaking": True}) # Forward raw 24kHz audio bytes directly await websocket.send_bytes(part.inline_data.data) elif part.text: print(f"[DEBUG] Gemini sent transcript: {part.text}", flush=True) current_model_text += part.text # Forward transcript text await websocket.send_json({ "type": "transcript",10 unmodified lines if getattr(response.server_content, "generation_complete", False) or getattr(response.server_content, "turn_complete", False): print("[DEBUG] Gemini generation / turn complete. Unmuting client microphone.", flush=True) await websocket.send_json({"type": "model_speaking", "speaking": False}) # Trigger asynchronous sentiment logging if current_user_text.strip(): asyncio.create_task( analyze_and_log_sentiment( session_id=session_id, user_text=current_user_text, model_text=current_model_text, api_key=api_key ) ) current_user_text = "" current_model_text = ""
# Handle Tool Calls (Editorial Dispute / Document Gen) if response.tool_call is not None:main.py+135-14