import gradio as gr import os import requests import json from typing import Dict, List # Configuration for HuggingFace Spaces - no environment variables needed # --- Configuration --- # Using the working Groq backend deployed on Modal MODAL_BACKEND_URL = "https://gebhardt-wolfh--patent-architect-groq-fastapi-app.modal.run" # --- Agent Personalities for Enhanced Demo --- AGENT_PERSONALITIES = { "Prior Art Agent": { "personality": "🕵️ Skeptical Detective", "thinking_style": "🔍 Hmm, let me dig deeper into this...", "catchphrase": "I've seen this before, but is it really the same?", "bias": "Find everything that could invalidate this patent", "negotiation_weight": 0.25 }, "Invention Summary Agent": { "personality": "📝 Technical Storyteller", "thinking_style": "✍️ How can I make this crystal clear...", "catchphrase": "Every invention has a story to tell", "bias": "Maximize technical clarity and innovation narrative", "negotiation_weight": 0.20 }, "Figure Drafter Agent": { "personality": "🎨 Visual Architect", "thinking_style": "🖼️ A picture is worth a thousand claims...", "catchphrase": "If you can't draw it, you can't patent it", "bias": "Ensure visual completeness and technical accuracy", "negotiation_weight": 0.15 }, "Claims Drafter Agent": { "personality": "⚖️ Legal Strategist", "thinking_style": "🧠 What's the broadest defensible scope...", "catchphrase": "Let's make this bulletproof!", "bias": "Balance broad protection with grantability", "negotiation_weight": 0.40 } } # IP Opportunity Categories IP_OPPORTUNITIES = [ {"type": "Adjacent Innovation", "icon": "🔗", "description": "Related inventions in the same field"}, {"type": "Cross-Industry Application", "icon": "🌐", "description": "Same tech, different industries"}, {"type": "Method Patents", "icon": "⚙️", "description": "Process and manufacturing methods"}, {"type": "Combination Patents", "icon": "🧩", "description": "Your invention + existing tech"}, {"type": "Defensive Patents", "icon": "🛡️", "description": "Block competitor strategies"} ] def create_agent_negotiation_display(agent_responses: List[Dict]) -> str: """Creates a visual display of agent negotiation and consensus building.""" html = """
{personality['thinking_style']}
Position: {personality['bias']}
"{personality['catchphrase']}"
Strategic Recommendation: Balanced approach with {consensus_level}% agent agreement
{opp['description']}
Market: {opp['market_size']}
🎯 Strategic Insight: Found {total} high-value patent opportunities worth ${total_value}B+ in market potential
{personality['thinking_style']}
{thought.replace(chr(10), '
')}
"{personality['catchphrase']}"
{thought.replace(chr(10), '
')}
Enter invention to discover patent opportunities
"), "negotiation": gr.HTML.update(value="Agents will negotiate optimal strategy
"), "prior_art": gr.Markdown.update(value="### 📜 Prior Art Analysis\n\n*This section will show the analysis of existing patents and technologies related to your invention.*"), "summary": gr.Markdown.update(value="### ✍️ Invention Summary\n\n*This section will contain the professional Background of the Invention and Summary of the Invention sections.*"), "figures": gr.Markdown.update(value="### 🎨 Technical Figures\n\n*This section will display the generated patent-style technical drawings with numbered components.*"), "claims": gr.Markdown.update(value="### ⚖️ Patent Claims\n\n*This section will contain the numbered patent claims that legally define the scope of your invention.*"), "status": "⚖️ Patent Architect v2 - Ready for strategic IP discovery", } yield list(outputs.values()) return if not MODAL_BACKEND_URL: error_msg = "⚠️ **Backend Configuration Required**\n\nPlease deploy the Patent Architect backend and update the `MODAL_BACKEND_URL` configuration." yield error_msg, error_msg, error_msg, error_msg, "❌ Configuration Error" return # Initialize all sections with enhanced features opportunities_html = create_ip_opportunity_cards(invention_disclosure) negotiation_html = "Preparing multi-agent strategy session...
" prior_art_section = "### 📜 Prior Art Analysis\n\n*🕵️ Skeptical Detective is searching patent databases...*" summary_section = "### ✍️ Invention Summary\n\n*📝 Technical Storyteller is awaiting prior art analysis...*" figures_section = "### 🎨 Technical Figures\n\n*🎨 Visual Architect is awaiting invention summary...*" claims_section = "### ⚖️ Patent Claims\n\n*⚖️ Legal Strategist is awaiting technical figures...*" status = "🚀 Starting Enhanced Patent Architect with IP Discovery..." yield opportunities_html, negotiation_html, prior_art_section, summary_section, figures_section, claims_section, status try: print(f"Connecting to Patent Architect backend: {MODAL_BACKEND_URL}") with requests.post( f"{MODAL_BACKEND_URL}/generate_patent", json={"invention_disclosure": invention_disclosure}, timeout=1800, # 30 minute timeout for full patent generation stream=True ) as response: response.raise_for_status() for line in response.iter_lines(): if line: decoded_line = line.decode('utf-8') if decoded_line.startswith('data: '): try: event = json.loads(decoded_line[6:]) event_status = event.get("status") if event_status == "starting": status = event.get("log", "Starting...") elif event_status == "running": status = event.get("log", "Processing...") elif event_status == "update": data = event.get("data", {}) step_info = event.get("step", "") section_type = data.get("section_type") agent_name = data.get("agent_name", "Patent Agent") content = data.get("content", "") thought = data.get("thought", "") sources = data.get("sources", []) image_urls = data.get("image_urls", []) formatted_content = format_patent_section(agent_name, content, thought, sources, image_urls) # Update the appropriate section based on the agent's designated section_type if section_type == "prior_art": prior_art_section = formatted_content summary_section = "### ✍️ Invention Summary\n\n*📝 Technical Storyteller is crafting your invention story...*" # Show negotiation visualization agent_responses = [{"name": agent_name}] negotiation_html = create_agent_negotiation_display(agent_responses) elif section_type == "summary": summary_section = formatted_content figures_section = "### 🎨 Technical Figures\n\n*🎨 Visual Architect is designing technical drawings...*" # Update negotiation with more agents agent_responses = [{"name": "Prior Art Agent"}, {"name": agent_name}] negotiation_html = create_agent_negotiation_display(agent_responses) elif section_type == "figures": figures_section = formatted_content claims_section = "### ⚖️ Patent Claims\n\n*⚖️ Legal Strategist is optimizing claim scope...*" # Update negotiation with more agents agent_responses = [{"name": "Prior Art Agent"}, {"name": "Invention Summary Agent"}, {"name": agent_name}] negotiation_html = create_agent_negotiation_display(agent_responses) elif section_type == "claims": claims_section = formatted_content # Final negotiation with all agents agent_responses = [ {"name": "Prior Art Agent"}, {"name": "Invention Summary Agent"}, {"name": "Figure Drafter Agent"}, {"name": agent_name} ] negotiation_html = create_agent_negotiation_display(agent_responses) # Enhanced status with agent personality if agent_name in AGENT_PERSONALITIES: personality = AGENT_PERSONALITIES[agent_name]["personality"] status = f"✅ **Step {step_info} Complete** - {personality} has finished their analysis" else: status = f"✅ **Step {step_info} Complete** - {agent_name} finished" elif event_status == "assembling": status = event.get("log", "Assembling patent application...") elif event_status == "complete": status = "🎉 **Patent Application Complete!** - Ready for review and filing" yield opportunities_html, negotiation_html, prior_art_section, summary_section, figures_section, claims_section, status except json.JSONDecodeError as e: print(f"Could not decode JSON from stream: {decoded_line}") continue except requests.exceptions.RequestException as e: error_msg = f"❌ **Connection Error:** {str(e)}\n\nPlease check that the Patent Architect backend is deployed and accessible." status = "❌ Connection Failed" yield opportunities_html, negotiation_html, prior_art_section, summary_section, figures_section, claims_section, status with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue"), title="⚖️ Patent Architect v2") as demo: gr.HTML("""AI IP Strategy Platform with Multi-Agent Intelligence
IP Discovery • Agent Negotiation • Strategic Claims • Competitive Intelligence
🚀 Beyond Patents: Strategic IP Portfolio Generation
Patent opportunities will appear here
") with gr.Column(): negotiation_display = gr.HTML("Multi-agent consensus will appear here
") gr.Markdown("---") gr.Markdown("## 📋 Optimized Patent Application") with gr.Tabs(): with gr.TabItem("📜 Prior Art Analysis"): prior_art_output = gr.Markdown( value="### 📜 Prior Art Analysis\n\n*This section will show the analysis of existing patents and technologies related to your invention.*" ) with gr.TabItem("✍️ Background & Summary"): summary_output = gr.Markdown( value="### ✍️ Invention Summary\n\n*This section will contain the professional Background of the Invention and Summary of the Invention sections.*" ) with gr.TabItem("🎨 Technical Figures"): figures_output = gr.Markdown( value="### 🎨 Technical Figures\n\n*This section will display the generated patent-style technical drawings with numbered components.*" ) with gr.TabItem("⚖️ Patent Claims"): claims_output = gr.Markdown( value="### ⚖️ Patent Claims\n\n*This section will contain the numbered patent claims that legally define the scope of your invention.*" ) generate_btn.click( fn=run_patent_architect_in_ui, inputs=[invention_input], outputs=[opportunities_display, negotiation_display, prior_art_output, summary_output, figures_output, claims_output, status_display] ) gr.Examples( [ ["A smart pill dispenser that uses computer vision to verify correct medication, sends alerts for missed doses, and connects to healthcare providers for monitoring compliance."], ["A modular vertical farming system with AI-controlled LED lighting that adapts spectrum and intensity based on plant growth stage, optimizing yield while reducing energy consumption."], ["A wearable device that monitors micro-expressions and vocal patterns to provide real-time feedback on presentation skills and confidence levels during public speaking."], ], inputs=[invention_input], label="💡 Example Invention Disclosures" ) gr.HTML(""" """) if __name__ == "__main__": print("⚖️ PATENT ARCHITECT - Frontend") print(f"✅ Connecting to backend: {MODAL_BACKEND_URL}") demo.queue().launch( share=True, favicon_path=None, # Disable favicon to prevent 404s show_error=False, # Hide error messages in UI quiet=True, # Reduce console output debug=False # Disable debug mode to reduce console noise )