Spaces:
Sleeping
Sleeping
Download main.py from SimblyPaul/Tron: direct link, hf CLI and curl.
- Browser
- Download file 43.6 kB
-
https://huggingface.co/spaces/SimblyPaul/Tron/resolve/main/main.py
- Command line
-
hf download hf://spaces/SimblyPaul/Tron/main.py
-
curl -L -o main.py https://huggingface.co/spaces/SimblyPaul/Tron/resolve/main/main.py
43.6 kB
| import os | |
| import uuid | |
| import traceback | |
| import json | |
| import smtplib | |
| import asyncio | |
| from datetime import datetime | |
| from email.mime.text import MIMEText | |
| from email.mime.multipart import MIMEMultipart | |
| from typing import List, Optional | |
| import requests | |
| from fastapi import FastAPI, Request, Form, UploadFile, File, WebSocket, WebSocketDisconnect, BackgroundTasks | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from fastapi.responses import HTMLResponse, FileResponse | |
| from fastapi.staticfiles import StaticFiles | |
| from fastapi.templating import Jinja2Templates | |
| from dotenv import load_dotenv | |
| import docx | |
| from docx import Document | |
| from docx.shared import Inches, Pt, RGBColor | |
| from docx.enum.text import WD_ALIGN_PARAGRAPH | |
| import pypdf | |
| from google import genai | |
| from google.genai import types | |
| def extract_text_from_pdf(file_path: str) -> str: | |
| """Extracts raw text from a PDF document (.pdf).""" | |
| try: | |
| reader = pypdf.PdfReader(file_path) | |
| text_content = [] | |
| for page in reader.pages: | |
| text = page.extract_text() | |
| if text: | |
| text_content.append(text) | |
| return "\n".join(text_content) | |
| except Exception as e: | |
| print(f"[ERROR] Failed to extract text from PDF: {e}") | |
| return "" | |
| # Load environment variables relative to main.py's directory location | |
| base_dir = os.getcwd() # Or relative to main.py | |
| base_dir = os.path.dirname(os.path.abspath(__file__)) | |
| dotenv_path = os.path.join(base_dir, ".env") | |
| load_dotenv(dotenv_path=dotenv_path, override=True) | |
| app = FastAPI(title="TRON - Voice-Activated News Prototype") | |
| # Enable CORS for cross-origin development or file:/// access | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| async def debug_exception_handler(request: Request, exc: Exception): | |
| print("[CRITICAL UNCAUGHT EXCEPTION]", flush=True) | |
| import traceback | |
| traceback.print_exc() | |
| return HTMLResponse(content=f"Internal Server Error: {exc}", status_code=500) | |
| # Ensure required static directories exist | |
| os.makedirs("static/notes", exist_ok=True) | |
| os.makedirs("static/uploads", exist_ok=True) | |
| os.makedirs("static/articles", exist_ok=True) | |
| # Initialize Firebase Admin SDK if credentials and bucket are configured in env | |
| firebase_initialized = False | |
| try: | |
| fb_creds_json = os.getenv("FIREBASE_CREDENTIALS") | |
| fb_bucket = os.getenv("FIREBASE_STORAGE_BUCKET") | |
| if fb_creds_json and fb_bucket: | |
| import firebase_admin | |
| from firebase_admin import credentials | |
| creds_dict = json.loads(fb_creds_json) | |
| cred = credentials.Certificate(creds_dict) | |
| firebase_admin.initialize_app(cred, { | |
| 'storageBucket': fb_bucket | |
| }) | |
| firebase_initialized = True | |
| print("[INFO] Firebase Admin SDK successfully initialized.", flush=True) | |
| else: | |
| print("[WARNING] Firebase environment variables not fully set. Running in local ephemeral mode.", flush=True) | |
| except Exception as e: | |
| print(f"[ERROR] Failed to initialize Firebase Admin SDK: {e}", flush=True) | |
| traceback.print_exc() | |
| def upload_to_firebase(local_path: str, destination_blob_name: str, content_type: str) -> Optional[str]: | |
| """Uploads a file to Firebase Storage and returns its public URL if successful.""" | |
| if not firebase_initialized: | |
| return None | |
| try: | |
| from firebase_admin import storage | |
| bucket = storage.bucket() | |
| blob = bucket.blob(destination_blob_name) | |
| blob.upload_from_filename(local_path, content_type=content_type) | |
| blob.make_public() | |
| return blob.public_url | |
| except Exception as e: | |
| print(f"[ERROR] Firebase upload failed for {local_path}: {e}", flush=True) | |
| traceback.print_exc() | |
| return None | |
| # Mount static folder for downloads and uploads | |
| app.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 database | |
| init_db() | |
| # Initialize Templates | |
| templates = Jinja2Templates(directory="templates") | |
| # Target model ID for Multimodal Live API | |
| MODEL_ID = "gemini-3.8-live" | |
| def extract_text_from_docx(file_path: str) -> str: | |
| """Extracts raw text from a Microsoft Word document (.docx).""" | |
| doc = Document(file_path) | |
| full_text = [] | |
| for para in doc.paragraphs: | |
| full_text.append(para.text) | |
| for table in doc.tables: | |
| for row in table.rows: | |
| for cell in row.cells: | |
| full_text.append(cell.text) | |
| return "\n".join(full_text) | |
| def create_note_docx(subject: str, content_summary: str, filepath: str): | |
| """Generates a professionally styled Microsoft Word document matching the editorial context.""" | |
| doc = Document() | |
| # Page Margins (1 inch) | |
| for section in doc.sections: | |
| section.top_margin = Inches(1) | |
| section.bottom_margin = Inches(1) | |
| section.left_margin = Inches(1) | |
| section.right_margin = Inches(1) | |
| # Title Section (Georgia Font - Times Replica) | |
| p = doc.add_paragraph() | |
| p.alignment = WD_ALIGN_PARAGRAPH.CENTER | |
| p.paragraph_format.space_after = Pt(2) | |
| run = p.add_run("TRON RESEARCH NOTE") | |
| run.font.name = 'Georgia' | |
| run.font.size = Pt(20) | |
| run.bold = True | |
| run.font.color.rgb = RGBColor(15, 23, 42) # Slate-900 | |
| # Subject Line | |
| p_sub = doc.add_paragraph() | |
| p_sub.alignment = WD_ALIGN_PARAGRAPH.CENTER | |
| p_sub.paragraph_format.space_after = Pt(12) | |
| run_sub = p_sub.add_run(f"Subject: {subject}") | |
| run_sub.font.name = 'Georgia' | |
| run_sub.font.size = Pt(12) | |
| run_sub.italic = True | |
| run_sub.font.color.rgb = RGBColor(71, 85, 105) # Slate-600 | |
| # Thin Divider | |
| p_div = doc.add_paragraph() | |
| p_div.alignment = WD_ALIGN_PARAGRAPH.CENTER | |
| p_div.paragraph_format.space_after = Pt(18) | |
| run_div = p_div.add_run("—" * 50) | |
| run_div.font.name = 'Georgia' | |
| run_div.font.color.rgb = RGBColor(203, 213, 225) # Slate-300 | |
| # Content Body | |
| for paragraph_text in content_summary.split('\n'): | |
| cleaned_text = paragraph_text.strip() | |
| if not cleaned_text: | |
| continue | |
| p_body = doc.add_paragraph() | |
| p_body.paragraph_format.line_spacing = 1.15 | |
| p_body.paragraph_format.space_after = Pt(8) | |
| run_body = p_body.add_run(cleaned_text) | |
| run_body.font.name = 'Georgia' | |
| run_body.font.size = Pt(11) | |
| run_body.font.color.rgb = RGBColor(30, 41, 59) # Slate-800 | |
| # Footer | |
| section = doc.sections[0] | |
| footer = section.footer | |
| f_p = footer.paragraphs[0] | |
| f_p.alignment = WD_ALIGN_PARAGRAPH.RIGHT | |
| run_footer = f_p.add_run(f"Generated by TRON Assistant Prototype • {datetime.now().strftime('%Y-%m-%d')}") | |
| run_footer.font.name = 'Georgia' | |
| run_footer.font.size = Pt(8) | |
| run_footer.font.color.rgb = RGBColor(148, 163, 184) # Slate-400 | |
| doc.save(filepath) | |
| def send_email_dispute(original_fact: str, suggested_correction: str) -> bool: | |
| """Sends an email summarizing the editorial dispute using credentials from the .env file.""" | |
| smtp_server = os.getenv("SMTP_SERVER", "smtp.gmail.com") | |
| try: | |
| smtp_port = int(os.getenv("SMTP_PORT", "587")) | |
| except: | |
| smtp_port = 587 | |
| sender_email = os.getenv("SENDER_EMAIL") | |
| sender_password = os.getenv("SENDER_PASSWORD") | |
| receiver_email = os.getenv("RECEIVER_EMAIL") | |
| if not sender_email or not sender_password or not receiver_email: | |
| print("[WARNING] SMTP configuration incomplete in .env. Logging dispute data to stdout:") | |
| print(f" - Original Fact: {original_fact}") | |
| print(f" - Suggested Correction: {suggested_correction}") | |
| return True # Fallback success for local development/mock environment | |
| msg = MIMEMultipart() | |
| msg['From'] = sender_email | |
| msg['To'] = receiver_email | |
| msg['Subject'] = f"TRON ALERT: Editorial Dispute Reported" | |
| body = f"""TRON EDITORIAL DISPUTE ALERT | |
| A reader has flagged an assertion in the investigative report during a voice-activated session. | |
| Original Fact Mentioned: | |
| "{original_fact}" | |
| Reader's Suggested Correction: | |
| "{suggested_correction}" | |
| Timestamp: {datetime.now().isoformat()} | |
| Please verify the claim and update the article source if necessary. | |
| """ | |
| msg.attach(MIMEText(body, 'plain')) | |
| if smtp_server.startswith("http://") or smtp_server.startswith("https://"): | |
| import requests | |
| payload = { | |
| "to": receiver_email, | |
| "subject": f"TRON ALERT: Editorial Dispute Reported", | |
| "body": body, | |
| "secret_key": sender_password | |
| } | |
| try: | |
| res = requests.post(smtp_server, json=payload, timeout=25) | |
| if res.status_code == 200: | |
| res_data = res.json() | |
| if res_data.get("success") or res_data.get("status") == "success": | |
| print("[INFO] Editorial dispute alert sent successfully via Web Gateway.", flush=True) | |
| return True | |
| else: | |
| print(f"[ERROR] Web Gateway returned error: {res_data}", flush=True) | |
| return False | |
| else: | |
| print(f"[ERROR] Web Gateway returned HTTP {res.status_code}: {res.text}", flush=True) | |
| return False | |
| except Exception as e: | |
| print(f"[ERROR] Failed to send email via Web Gateway: {e}", flush=True) | |
| return False | |
| try: | |
| if smtp_port == 465: | |
| server = smtplib.SMTP_SSL(smtp_server, smtp_port, timeout=10) | |
| else: | |
| server = smtplib.SMTP(smtp_server, smtp_port, timeout=10) | |
| server.starttls() | |
| server.login(sender_email, sender_password) | |
| server.sendmail(sender_email, receiver_email, msg.as_string()) | |
| server.quit() | |
| print("[INFO] Editorial dispute alert email sent successfully.") | |
| return True | |
| except Exception as e: | |
| print(f"[ERROR] Failed to send dispute email: {e}") | |
| return False | |
| # ROUTES | |
| async def dashboard_home(request: Request): | |
| """Renders the main Creator Dashboard.""" | |
| return templates.TemplateResponse(request=request, name="dashboard.html") | |
| async def construct_article( | |
| request: Request, | |
| background_tasks: BackgroundTasks, | |
| headline: str = Form(...), | |
| author: str = Form(...), | |
| date: str = Form(...), | |
| body: str = Form(...), | |
| persona: str = Form(...), | |
| grounding: str = Form(...), | |
| grounding_instructions: str = Form(""), | |
| voice: str = Form(...), | |
| greeting: str = Form(...), | |
| silence_duration_ms: int = Form(1000), | |
| custom_backend_url: Optional[str] = Form(None), | |
| files: Optional[List[UploadFile]] = File(None) | |
| ): | |
| """Ingests files, caches them in the Gemini Files API, and compiles the standalone HTML article.""" | |
| api_key = os.getenv("GEMINI_API_KEY") | |
| if not api_key: | |
| return HTMLResponse("Error: GEMINI_API_KEY is not set in the server's .env file.", status_code=500) | |
| # Set up the article itself as the primary grounding context | |
| document_context = ( | |
| f"--- Article Headline: {headline} ---\n" | |
| f"--- Author: {author} ---\n" | |
| f"--- Date: {date} ---\n" | |
| f"--- Article Content ---\n{body}\n" | |
| ) | |
| # Process files and extract text for context | |
| print(f"[DEBUG] Received files: {[f.filename for f in files] if files else 'None'}", flush=True) | |
| if files: | |
| extracted_texts = [] | |
| for uploaded_file in files: | |
| if uploaded_file.filename == "": | |
| continue | |
| # Save file locally to temp path | |
| temp_filename = f"{uuid.uuid4().hex}_{uploaded_file.filename}" | |
| temp_path = os.path.join("static", "uploads", temp_filename) | |
| with open(temp_path, "wb") as buffer: | |
| content = await uploaded_file.read() | |
| buffer.write(content) | |
| try: | |
| filename_lower = uploaded_file.filename.lower() | |
| if filename_lower.endswith(".docx"): | |
| text_content = extract_text_from_docx(temp_path) | |
| print(f"[DEBUG] Extracted {len(text_content)} chars from Word doc: {uploaded_file.filename}", flush=True) | |
| extracted_texts.append(f"--- Research Document Content: {uploaded_file.filename} ---\n{text_content}\n") | |
| elif filename_lower.endswith(".pdf"): | |
| text_content = extract_text_from_pdf(temp_path) | |
| print(f"[DEBUG] Extracted {len(text_content)} chars from PDF: {uploaded_file.filename}", flush=True) | |
| extracted_texts.append(f"--- Research Document Content: {uploaded_file.filename} ---\n{text_content}\n") | |
| else: | |
| print(f"[DEBUG] Unsupported file extension for file: {uploaded_file.filename}", flush=True) | |
| except Exception as e: | |
| print(f"[ERROR] Failed to extract text from {uploaded_file.filename}: {e}", flush=True) | |
| traceback.print_exc() | |
| finally: | |
| # Clean up local temporary file | |
| try: os.remove(temp_path) | |
| except: pass | |
| if extracted_texts: | |
| document_context += "\n" + "\n".join(extracted_texts) | |
| print(f"[DEBUG] Total document_context size: {len(document_context)} characters", flush=True) | |
| # Build system instructions based on constraints | |
| system_instruction = persona | |
| 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, | |
| "article_id": article_filename.split(".html")[0] | |
| } | |
| # Determine backend URL: use custom_backend_url if provided, otherwise derive it dynamically | |
| if custom_backend_url and custom_backend_url.strip(): | |
| url_str = custom_backend_url.strip() | |
| if url_str.startswith("https://"): | |
| backend_url = url_str.replace("https://", "wss://") | |
| elif url_str.startswith("http://"): | |
| backend_url = url_str.replace("http://", "ws://") | |
| elif not url_str.startswith("ws://") and not url_str.startswith("wss://"): | |
| backend_url = f"wss://{url_str}" | |
| else: | |
| backend_url = url_str | |
| # Ensure it ends with /ws/live | |
| if not backend_url.endswith("/ws/live"): | |
| backend_url = backend_url.rstrip("/") + "/ws/live" | |
| else: | |
| # Automatically derive ws endpoint backend URL | |
| host_header = request.headers.get("host", "localhost:49999") | |
| proto = request.headers.get("x-forwarded-proto", request.url.scheme) | |
| protocol = "wss" if proto == "https" else "ws" | |
| backend_url = f"{protocol}://{host_header}/ws/live" | |
| # Render template using Jinja2 | |
| template_response = templates.TemplateResponse( | |
| request=request, | |
| name="article_template.html", | |
| context={ | |
| "headline": headline, | |
| "author": author, | |
| "date": date, | |
| "body": body, | |
| "backend_url": backend_url, | |
| "tron_config": tron_config | |
| } | |
| ) | |
| # Read the rendered template response | |
| html_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) | |
| # Upload to Firebase if initialized | |
| fb_url = upload_to_firebase(article_path, f"articles/{article_filename}", "text/html") | |
| if fb_url: | |
| shareable_url = fb_url | |
| else: | |
| # Build public shareable URL, respecting custom_backend_url if provided | |
| if custom_backend_url and custom_backend_url.strip(): | |
| custom_host = custom_backend_url.strip() | |
| for prefix in ["wss://", "ws://", "https://", "http://"]: | |
| if custom_host.startswith(prefix): | |
| custom_host = custom_host[len(prefix):] | |
| custom_host = custom_host.split("/")[0] # Get host domain only | |
| # Determine protocol scheme | |
| proto = "https" if ("https" in custom_backend_url or "wss" in custom_backend_url) else "http" | |
| shareable_url = f"{proto}://{custom_host}/static/articles/{article_filename}" | |
| else: | |
| host_header = request.headers.get("host", "localhost:49999") | |
| proto = request.headers.get("x-forwarded-proto", request.url.scheme) | |
| shareable_url = f"{proto}://{host_header}/static/articles/{article_filename}" | |
| print(f"[DEBUG] Constructed permanent article hosted at: {shareable_url}", flush=True) | |
| return { | |
| "success": True, | |
| "shareable_url": shareable_url, | |
| "filename": article_filename | |
| } | |
| # ANALYTICS DASHBOARD PORTAL & API ENDPOINTS | |
| async def admin_analytics_page(request: Request): | |
| return templates.TemplateResponse(request=request, name="admin_analytics.html") | |
| async def api_analytics_data(): | |
| return get_analytics_data() | |
| async def api_session_timeline(session_id: str): | |
| return get_session_timeline(session_id) | |
| 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 | |
| async def websocket_endpoint(websocket: WebSocket): | |
| await websocket.accept() | |
| print("[DEBUG] WebSocket connection accepted.", flush=True) | |
| api_key = os.getenv("GEMINI_API_KEY") | |
| if not api_key: | |
| print("[ERROR] GEMINI_API_KEY is not configured.", flush=True) | |
| 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() | |
| config_payload = json.loads(setup_data) | |
| if config_payload.get("type") != "setup": | |
| print("[ERROR] First message was not setup.", flush=True) | |
| await websocket.close(code=1008, reason="First message must be setup configurations.") | |
| return | |
| except Exception as e: | |
| print(f"[ERROR] Setup configuration failed: {e}", flush=True) | |
| await websocket.close(code=1008, reason=f"Setup failed: {e}") | |
| return | |
| voice_name = config_payload.get("voice", "Fenrir") | |
| system_instruction = config_payload.get("system_instruction", "") | |
| greeting = config_payload.get("greeting", "Hello!") | |
| 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. 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} | |
| # Establish Tools configuration | |
| tools = [ | |
| types.Tool( | |
| function_declarations=[ | |
| types.FunctionDeclaration( | |
| name="send_editorial_dispute", | |
| description=( | |
| "Triggers an email notification if a reader reports that a fact " | |
| "in the investigative report is wrong, incorrect, or suggests a layout correction." | |
| ), | |
| parameters=types.Schema( | |
| type=types.Type.OBJECT, | |
| properties={ | |
| "original_fact": types.Schema( | |
| type=types.Type.STRING, | |
| description="The original fact/assertion from the article that the reader disputes." | |
| ), | |
| "suggested_correction": types.Schema( | |
| type=types.Type.STRING, | |
| description="The correction or feedback suggested by the reader." | |
| ) | |
| }, | |
| required=["original_fact", "suggested_correction"] | |
| ) | |
| ), | |
| types.FunctionDeclaration( | |
| name="generate_document_note", | |
| description=( | |
| "Generates a Microsoft Word document note or summary about a specific sub-issue " | |
| "within the article or context documents when requested by the user, returning a download link." | |
| ), | |
| parameters=types.Schema( | |
| type=types.Type.OBJECT, | |
| properties={ | |
| "subject": types.Schema( | |
| type=types.Type.STRING, | |
| description="The subject or topic of the note/summary." | |
| ), | |
| "content_summary": types.Schema( | |
| type=types.Type.STRING, | |
| description="A detailed summary of the sub-issue synthesized from the context documents." | |
| ) | |
| }, | |
| required=["subject", "content_summary"] | |
| ) | |
| ) | |
| ] | |
| ) | |
| ] | |
| # Append document context to system instructions for RAG grounding in Live API | |
| if document_context: | |
| system_instruction += ( | |
| "\n\nSTRICT GROUNDING CONTEXT (RAG KNOWLEDGE BASE):\n" | |
| "==================================================\n" | |
| f"{document_context}\n" | |
| "==================================================\n" | |
| "You must strictly ground your responses using ONLY the details inside the files/context above." | |
| ) | |
| # Live Connect Config | |
| live_config = types.LiveConnectConfig( | |
| response_modalities=[types.Modality.AUDIO], | |
| system_instruction=types.Content( | |
| parts=[types.Part(text=system_instruction)] | |
| ), | |
| tools=tools, | |
| speech_config=types.SpeechConfig( | |
| voice_config=types.VoiceConfig( | |
| prebuilt_voice_config=types.PrebuiltVoiceConfig( | |
| voice_name=voice_name | |
| ) | |
| ) | |
| ), | |
| input_audio_transcription=types.AudioTranscriptionConfig(), | |
| output_audio_transcription=types.AudioTranscriptionConfig(), | |
| realtime_input_config=types.RealtimeInputConfig( | |
| automatic_activity_detection=types.AutomaticActivityDetection( | |
| silence_duration_ms=silence_duration_ms | |
| ) | |
| ) | |
| ) | |
| try: | |
| print("[DEBUG] Connecting to Gemini Live API...", flush=True) | |
| # Establish persistent Live connection to Gemini Live API | |
| async with client.aio.live.connect(model=MODEL_ID, config=live_config) as session: | |
| print("[DEBUG] Connected to Gemini Live API!", flush=True) | |
| # 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() | |
| if data.get("type") == "websocket.disconnect": | |
| print(f"[DEBUG] Client disconnected cleanly (code: {data.get('code', 1000)})", flush=True) | |
| raise WebSocketDisconnect(code=data.get("code", 1000)) | |
| if "bytes" in data: | |
| if state["in_tool_call"]: | |
| continue | |
| # Calculate max amplitude for diagnostics | |
| import struct | |
| raw_bytes = data["bytes"] | |
| max_val = 0 | |
| if len(raw_bytes) >= 2: | |
| count = len(raw_bytes) // 2 | |
| ints = struct.unpack(f"<{count}h", raw_bytes[:count*2]) | |
| max_val = max(abs(x) for x in ints) | |
| print(f"[DEBUG] Received audio chunk: {len(raw_bytes)} bytes, Max Amp: {max_val}", flush=True) | |
| await session.send_realtime_input( | |
| audio=types.Blob( | |
| data=raw_bytes, | |
| mime_type="audio/pcm;rate=16000" | |
| ) | |
| ) | |
| elif "text" in data: | |
| if state["in_tool_call"]: | |
| print("[DEBUG] Skipping client text input during active tool call.", flush=True) | |
| continue | |
| print(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: | |
| raise | |
| except Exception as e: | |
| print(f"[DEBUG] Error receiving from client: {e}", flush=True) | |
| traceback.print_exc() | |
| 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(): | |
| # Handle content output (Audio and Text) | |
| if response.server_content is not None: | |
| # 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, | |
| "finished": getattr(t, "finished", False) | |
| }) | |
| if getattr(response.server_content, "interim_input_transcription", None) is not None: | |
| t = response.server_content.interim_input_transcription | |
| await websocket.send_json({ | |
| "type": "interim_input_transcription", | |
| "text": t.text, | |
| "finished": getattr(t, "finished", False) | |
| }) | |
| 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) | |
| }) | |
| 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", | |
| "text": part.text | |
| }) | |
| # Handle barge-in/interruption | |
| if response.server_content.interrupted: | |
| print("[DEBUG] Gemini detected interruption / barge-in.", flush=True) | |
| await websocket.send_json({"type": "model_speaking", "speaking": False}) | |
| await websocket.send_json({"type": "interrupted"}) | |
| # Handle turn complete / generation complete to unmute the microphone | |
| 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: | |
| state["in_tool_call"] = True | |
| try: | |
| for call in response.tool_call.function_calls: | |
| print(f"[DEBUG] Gemini triggered tool call: {call.name}", flush=True) | |
| if call.name == "send_editorial_dispute": | |
| orig_fact = call.args.get("original_fact", "") | |
| sugg_corr = call.args.get("suggested_correction", "") | |
| # Execute dispute email | |
| success = send_email_dispute(orig_fact, sugg_corr) | |
| # Respond to Gemini model | |
| await session.send_tool_response( | |
| function_responses=[ | |
| types.FunctionResponse( | |
| name=call.name, | |
| id=call.id, | |
| response={"success": success} | |
| ) | |
| ] | |
| ) | |
| # Notify client to render alert banner | |
| await websocket.send_json({ | |
| "type": "dispute_triggered", | |
| "original_fact": orig_fact, | |
| "suggested_correction": sugg_corr | |
| }) | |
| elif call.name == "generate_document_note": | |
| subject = call.args.get("subject", "Research Summary") | |
| content_summary = call.args.get("content_summary", "") | |
| # Generate docx note | |
| note_id = uuid.uuid4().hex[:8] | |
| filename = f"note_{note_id}.docx" | |
| filepath = os.path.join("static", "notes", filename) | |
| create_note_docx(subject, content_summary, filepath) | |
| # Upload to Firebase if initialized | |
| fb_url = upload_to_firebase(filepath, f"notes/{filename}", "application/vnd.openxmlformats-officedocument.wordprocessingml.document") | |
| if fb_url: | |
| download_url = fb_url | |
| else: | |
| # Construct download link using derived websocket URL | |
| ws_url = str(websocket.url) | |
| http_url = ws_url.replace("wss://", "https://").replace("ws://", "http://") | |
| base_url = http_url.split("/ws/live")[0] | |
| download_url = f"{base_url}/static/notes/{filename}" | |
| # Respond to Gemini model | |
| await session.send_tool_response( | |
| function_responses=[ | |
| types.FunctionResponse( | |
| name=call.name, | |
| id=call.id, | |
| response={ | |
| "success": True, | |
| "download_url": download_url | |
| } | |
| ) | |
| ] | |
| ) | |
| # Notify client to display download button | |
| await websocket.send_json({ | |
| "type": "document_ready", | |
| "subject": subject, | |
| "download_url": download_url | |
| }) | |
| finally: | |
| state["in_tool_call"] = False | |
| # Yield control to prevent CPU spinning if session.receive() exits immediately | |
| await asyncio.sleep(0.01) | |
| except WebSocketDisconnect: | |
| raise | |
| except Exception as e: | |
| print(f"[DEBUG] Error sending to client: {e}", flush=True) | |
| traceback.print_exc() | |
| # Start listener loops concurrently first so we don't miss the initial response stream | |
| receive_task = asyncio.create_task(receive_from_client()) | |
| send_task = asyncio.create_task(send_to_client()) | |
| # Trigger the custom greeting message | |
| greeting_prompt = ( | |
| f"Please greet the user now. Speak out loud exactly this greeting: \"{greeting}\" " | |
| "Do not add any additional greetings or extra chatter. Immediately ask the user if they want you to read the news article." | |
| ) | |
| print("[DEBUG] Sending greeting prompt to Gemini...", flush=True) | |
| # Notify the client that the model is preparing to speak | |
| await websocket.send_json({"type": "model_speaking", "speaking": True}) | |
| await session.send_client_content( | |
| turns=types.Content( | |
| role="user", | |
| parts=[types.Part(text=greeting_prompt)] | |
| ), | |
| turn_complete=True | |
| ) | |
| # Signal the client that setup is complete | |
| print("[DEBUG] Ready signal sent to client.", flush=True) | |
| await websocket.send_json({"type": "ready"}) | |
| # Wait for the loops to finish or fail | |
| done, pending = await asyncio.wait( | |
| [receive_task, send_task], | |
| return_when=asyncio.FIRST_COMPLETED | |
| ) | |
| print(f"[DEBUG] One of the loops completed. Done: {done}", flush=True) | |
| for task in pending: | |
| task.cancel() | |
| except WebSocketDisconnect: | |
| print("[DEBUG] WebSocketDisconnect propagated to outer scope.", flush=True) | |
| except Exception as e: | |
| print(f"[ERROR] Session connection exception: {e}", flush=True) | |
| traceback.print_exc() | |
| try: | |
| await websocket.send_json({"type": "transcript", "text": f"[Error connecting to Gemini Live API: {e}]"}) | |
| except: | |
| pass | |
| finally: | |
| await websocket.close() | |