Spaces:
Sleeping
Sleeping
Upload main.py
Browse files7 unmodified lines891011121395 unmodified lines109110111112113114115116117118119234 unmodified lines35435535635735835936036136236336436536636 unmodified lines40340440540640740840927 unmodified lines4374384394404414427 unmodified lines45045145245345445513 unmodified lines46947047147247347447590 unmodified lines56656756856957057126 unmodified lines5985996006016026036046056066076086096102 unmodified lines6136146156166176182 unmodified lines6216226236246256268 unmodified lines63563663763863964064164264364464564664764864965065165265365465565665710 unmodified lines6686696706716726737 unmodified linesfrom email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipartfrom typing import List, Optionalfrom 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")# Initialize Templatestemplates = Jinja2Templates(directory="templates")# Target model ID for Multimodal Live APIMODEL_ID = "gemini-3.1-flash-live-preview"def extract_text_from_docx(file_path: str) -> str:"""Extracts raw text from a Microsoft Word document (.docx)."""234 unmodified linesif grounding == "true" and grounding_instructions.strip():system_instruction += f"\n\nSTRICT GROUNDING & CONTEXT BOUNDING RULES:\n{grounding_instructions}"# Dynamic JSON config to embed inside downloaded filetron_config = {"voice": voice,"system_instruction": system_instruction,"greeting": greeting,"document_context": document_context,"silence_duration_ms": silence_duration_ms}# Determine backend URL: use custom_backend_url if provided, otherwise derive it dynamically36 unmodified lineshtml_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}# WEBSOCKET BI-DIRECTIONAL BRIDGE@app.websocket("/ws/live")7 unmodified linesawait websocket.close(code=1008, reason="GEMINI_API_KEY not configured in .env file.")return# Wait for the client to send the setup configurationtry:setup_data = await websocket.receive_text()13 unmodified linesdocument_context = config_payload.get("document_context", "")silence_duration_ms = config_payload.get("silence_duration_ms", 1000)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)client = genai.Client(api_key=api_key)state = {"in_tool_call": False}90 unmodified lines# Bidirectional forwarding loopsasync def receive_from_client():"""Loop: Receive 16kHz PCM audio bytes from browser and forward to Gemini Live session."""try:while True:data = await websocket.receive()26 unmodified linesprint(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)except WebSocketDisconnect:raiseexcept Exception as e:2 unmodified linesasync def send_to_client():"""Loop: Receive responses/tool calls from Gemini Live session and forward/process them."""try:while True:async for response in session.receive():2 unmodified lines# Forward transcription eventsif getattr(response.server_content, "input_transcription", None) is not None:t = response.server_content.input_transcriptionawait 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_transcriptionawait websocket.send_json({"type": "output_transcription","text": t.text,"finished": getattr(t, "finished", False)})# Let client know model is actively speakingawait websocket.send_json({"type": "model_speaking", "speaking": True})model_turn = response.server_content.model_turnif model_turn is not None:for part in model_turn.parts:if part.inline_data is not None:# Forward raw 24kHz audio bytes directlyawait websocket.send_bytes(part.inline_data.data)elif part.text:print(f"[DEBUG] Gemini sent transcript: {part.text}", flush=True)# Forward transcript textawait websocket.send_json({"type": "transcript",10 unmodified linesif 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})# Handle Tool Calls (Editorial Dispute / Document Gen)if response.tool_call is not None:7 unmodified lines89101112131495 unmodified lines110111112113114115116117118119120121122123124234 unmodified lines35936036136236336436536636736836937037137237337436 unmodified lines41141241341441541627 unmodified lines4444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275287 unmodified lines53653753853954054154254354454554654754854955055113 unmodified lines56556656756856957057157257357457557657757857990 unmodified lines67067167267367467567626 unmodified lines7037047057067077087097107117127132 unmodified lines7167177187197207217222 unmodified lines7257267277287297307317328 unmodified lines74174274374474574674774874975075175275375475575675775875976076176276376476510 unmodified lines7767777787797807817827837847857867877887897907917927937947 unmodified linesfrom email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipartfrom typing import List, Optionalimport requestsfrom 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.8-live"def extract_text_from_docx(file_path: str) -> str:"""Extracts raw text from a Microsoft Word document (.docx)."""234 unmodified linesif 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 filetron_config = {"voice": voice,"system_instruction": system_instruction,"greeting": greeting,"document_context": document_context,"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 lineshtml_content = template_response.body.decode("utf-8")# Save the compiled HTML file permanently under static/articles/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 IPsreal_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():returnprompt = (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 backgroundloop = 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.textresp_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 linesawait websocket.close(code=1008, reason="GEMINI_API_KEY not configured in .env file.")return# Extract query params for session RAG trackingquery_params = websocket.query_paramsarticle_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 configurationtry:setup_data = await websocket.receive_text()13 unmodified linesdocument_context = config_payload.get("document_context", "")silence_duration_ms = config_payload.get("silence_duration_ms", 1000)# Log session connection metadata and geo locationclient_ip = websocket.client.hostforwarded_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. 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 loopsasync def receive_from_client():"""Loop: Receive 16kHz PCM audio bytes from browser and forward to Gemini Live session."""nonlocal current_user_texttry:while True:data = await websocket.receive()26 unmodified linesprint(f"[DEBUG] Received text message from client: {data['text']}", flush=True)msg = json.loads(data["text"])if msg.get("type") == "input_text":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:raiseexcept Exception as e:2 unmodified linesasync def send_to_client():"""Loop: Receive responses/tool calls from Gemini Live session and forward/process them."""nonlocal current_user_text, current_model_texttry:while True:async for response in session.receive():2 unmodified lines# Forward transcription eventsif getattr(response.server_content, "input_transcription", None) is not None:t = response.server_content.input_transcriptionif t.text:current_user_text = t.textawait 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_transcriptionif t.text:current_model_text = t.textawait websocket.send_json({"type": "output_transcription","text": t.text,"finished": getattr(t, "finished", False)})model_turn = response.server_content.model_turnif 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 audioawait websocket.send_json({"type": "model_speaking", "speaking": True})# Forward raw 24kHz audio bytes directlyawait 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 textawait websocket.send_json({"type": "transcript",10 unmodified linesif 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 loggingif 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