Spaces:
Sleeping
Sleeping
Upload main.py
Browse files429 unmodified lines43043143243343443555 unmodified lines49149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252331 unmodified lines55555655755855956010 unmodified lines57157257357457557670 unmodified lines647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716429 unmodified linesprint(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)# Establish Tools configurationtools = [55 unmodified lines"You must strictly ground your responses using ONLY the details inside the files/context above.")safety_settings = [types.SafetySetting(category="HARM_CATEGORY_HARASSMENT",threshold="BLOCK_NONE"),types.SafetySetting(category="HARM_CATEGORY_HATE_SPEECH",threshold="BLOCK_NONE"),types.SafetySetting(category="HARM_CATEGORY_SEXUALLY_EXPLICIT",threshold="BLOCK_NONE"),types.SafetySetting(category="HARM_CATEGORY_DANGEROUS_CONTENT",threshold="BLOCK_NONE"),types.SafetySetting(category="HARM_CATEGORY_CIVIC_INTEGRITY",threshold="BLOCK_NONE"),]# Live Connect Configlive_config = types.LiveConnectConfig(response_modalities=[types.Modality.AUDIO],safety_settings=safety_settings,system_instruction=types.Content(parts=[types.Part(text=system_instruction)]),31 unmodified linesraise WebSocketDisconnect(code=data.get("code", 1000))if "bytes" in data:# Calculate max amplitude for diagnosticsimport structraw_bytes = data["bytes"]10 unmodified lines))elif "text" in data:print(f"[DEBUG] Received text message from client: {data['text']}", flush=True)msg = json.loads(data["text"])if msg.get("type") == "input_text":70 unmodified lines# Handle Tool Calls (Editorial Dispute / Document Gen)if response.tool_call is not None: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 emailsuccess = send_email_dispute(orig_fact, sugg_corr)# Respond to Gemini modelawait session.send_tool_response(function_responses=[types.FunctionResponse(name=call.name,id=call.id,response={"success": success})])# Notify client to render alert bannerawait 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 notenote_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)# Construct download link using derived websocket URLws_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 modelawait 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 buttonawait websocket.send_json({"type": "document_ready","subject": subject,"download_url": download_url})# Yield control to prevent CPU spinning if session.receive() exits immediatelyawait asyncio.sleep(0.01)429 unmodified lines43043143243343443543655 unmodified lines49249349449549649749849950031 unmodified lines53253353453553653753853910 unmodified lines55055155255355455555655755870 unmodified lines629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702429 unmodified linesprint(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}# Establish Tools configurationtools = [55 unmodified lines"You must strictly ground your responses using ONLY the details inside the files/context above.")# Live Connect Configlive_config = types.LiveConnectConfig(response_modalities=[types.Modality.AUDIO],system_instruction=types.Content(parts=[types.Part(text=system_instruction)]),31 unmodified linesraise WebSocketDisconnect(code=data.get("code", 1000))if "bytes" in data:if state["in_tool_call"]:continue# Calculate max amplitude for diagnosticsimport structraw_bytes = data["bytes"]10 unmodified lines))elif "text" in data:if state["in_tool_call"]:print("[DEBUG] Skipping client text input during active tool call.", flush=True)continueprint(f"[DEBUG] Received text message from client: {data['text']}", flush=True)msg = json.loads(data["text"])if msg.get("type") == "input_text":70 unmodified lines# Handle Tool Calls (Editorial Dispute / Document Gen)if response.tool_call is not None:state["in_tool_call"] = Truetry: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 emailsuccess = send_email_dispute(orig_fact, sugg_corr)# Respond to Gemini modelawait session.send_tool_response(function_responses=[types.FunctionResponse(name=call.name,id=call.id,response={"success": success})])# Notify client to render alert bannerawait 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 notenote_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)# Construct download link using derived websocket URLws_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 modelawait 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 buttonawait 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 immediatelyawait asyncio.sleep(0.01)
main.py+74-88