Patent-Scout / app.py
hasanbasbunar's picture
switch model s
0b64b37
import gradio as gr
import pandas as pd
from openai import OpenAI
from pydantic import BaseModel
import os
import logging
import time
import json
import plotly.graph_objects as go
import plotly.express as px
import numpy as np
import pycountry
from collections import Counter
from types import SimpleNamespace
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[logging.StreamHandler()]
)
# --- Pydantic Data Models ---
class PatentRating(BaseModel):
"""Details the evaluation criteria for a patent on a scale of 1 to 10."""
novelty: int
inventive_step: int
utility: int
completeness: int
clarity: int
class Patent(BaseModel):
"""Represents the details of a relevant existing patent."""
id: str
title: str
company_name: str
date: str
country: str
relevance: str
class PatentExtraction(BaseModel):
"""Structures the final patentability analysis result."""
strengths: list[str]
weaknesses: list[str]
patent_rating: PatentRating
relevant_patents: list[Patent]
class RewrittenQuery(BaseModel):
"""Represents the product description, rewritten to be more formal."""
product_description: str
# --- Radar Chart Functions ---
def get_pleasant_color_for_value(value, alpha=0.7):
"""
Maps a value from 0-10 to a colour.
- 0 is a soft coral red
- 5 is a warm yellow
- 10 is a calming teal green
"""
red_color = np.array([239, 83, 80])
yellow_color = np.array([253, 216, 53])
green_color = np.array([38, 166, 154])
# Interpolate colours.
if value < 5:
ratio = value / 5
color = red_color + ratio * (yellow_color - red_color)
else:
ratio = (value - 5) / 5
color = yellow_color + ratio * (green_color - yellow_color)
return f'rgba({int(color[0])}, {int(color[1])}, {int(color[2])}, {alpha})'
def create_radar_plot(patent_rating: PatentRating):
"""
Creates and returns a Plotly radar plot with the fill color
based on the average of the radial values.
"""
# Extract values from PatentRating object
r_values = [
patent_rating.novelty,
patent_rating.inventive_step,
patent_rating.utility,
patent_rating.completeness,
patent_rating.clarity
]
theta_categories = ['Nouveauté', 'Étape inventive', 'Utilité', 'Complétude', 'Clarté']
# Close area loop
plot_r = r_values + [r_values[0]]
plot_theta = theta_categories + [theta_categories[0]]
# Use average value for area colour.
average_value = np.mean(r_values)
fill_color = get_pleasant_color_for_value(average_value)
# Create the radar plot figure
fig = go.Figure(data=go.Scatterpolar(
r=plot_r,
theta=plot_theta,
fill='toself',
fillcolor=fill_color,
line=dict(color='rgba(0, 0, 0, 0)')
))
# Update the layout of the plot
fig.update_layout(
template='plotly_white',
polar=dict(
radialaxis=dict(
layer='below traces',
visible=True,
range=[0, 10],
showticklabels=False,
ticks=''
),
angularaxis=dict(
tickfont=dict(size=14) # Police plus grande pour les labels
),
domain=dict(x=[0.1, 0.9], y=[0.1, 0.9]) # Réduire la taille du radar pour plus d'espace aux labels
),
showlegend=False,
# Show the average value as a large, bold annotation in the center
annotations=[
go.layout.Annotation(
text=f'<b>{average_value:.1f}</b>',
x=0.5,
y=0.5,
xref='paper',
yref='paper',
showarrow=False,
font=dict(
size=36,
color="#333333"
)
)
],
title=f'Score Moyen de Brevetabilité: {average_value:.2f}/10',
font=dict(size=12),
# Plus d'espace pour les labels
margin=dict(l=40, r=40, t=60, b=40),
height=450, # Hauteur fixe pour un bon ratio
autosize=True
)
return fig
# --- Map Functions ---
def generate_country_map(patents_data):
"""
Generates a world map showing the frequency of countries from patent data.
Args:
patents_data: List of patent dictionaries with 'country' field
Returns:
A Plotly figure object.
"""
if not patents_data:
# Create empty map if no data
fig = px.scatter_geo(
[],
projection="orthographic",
)
fig.update_layout(
title="Aucun brevet trouvé",
title_x=0.5,
paper_bgcolor='rgba(0,0,0,0)',
plot_bgcolor='rgba(0,0,0,0)',
)
fig.update_geos(
bgcolor='rgba(0,0,0,0)',
showocean=True,
oceancolor="lightblue",
lakecolor="lightblue"
)
return fig
# Extract country codes from patents
country_codes = [patent.get('country', '').strip().upper() for patent in patents_data if patent.get('country')]
country_counts = Counter(country_codes)
# Mapping for special patent codes
special_patent_codes = {
'EP': {'name': 'Union Européenne (EP)', 'iso3': 'EUR', 'lat': 50.8503, 'lon': 4.3517}, # Brussels
'WO': {'name': 'Organisation Mondiale (WO)', 'iso3': 'CHE', 'lat': 46.5197, 'lon': 6.6323}, # Geneva
'PCT': {'name': 'Traité PCT', 'iso3': 'CHE', 'lat': 46.5197, 'lon': 6.6323}, # Geneva
}
map_data = []
invalid_codes = set()
for code, count in country_counts.items():
# Check if it's a special patent code first
if code in special_patent_codes:
special = special_patent_codes[code]
map_data.append({
"iso_alpha": special['iso3'],
"country_name": special['name'],
"count": count,
"code_2": code,
"lat": special['lat'],
"lon": special['lon'],
"is_special": True
})
else:
# Try standard country codes
try:
country = pycountry.countries.get(alpha_2=code)
if country:
map_data.append({
"iso_alpha": country.alpha_3,
"country_name": country.name,
"count": count,
"code_2": code,
"is_special": False
})
else:
invalid_codes.add(code)
except (AttributeError, LookupError):
invalid_codes.add(code)
if not map_data:
# Create empty map if no valid countries
fig = px.scatter_geo(
[],
projection="orthographic",
)
fig.update_layout(
title="Aucun pays valide trouvé",
title_x=0.5,
paper_bgcolor='rgba(0,0,0,0)',
plot_bgcolor='rgba(0,0,0,0)',
)
fig.update_geos(
bgcolor='rgba(0,0,0,0)',
showocean=True,
oceancolor="lightblue",
lakecolor="lightblue"
)
return fig
# Separate regular countries and special patent locations
regular_data = [d for d in map_data if not d.get('is_special', False)]
special_data = [d for d in map_data if d.get('is_special', False)]
fig = px.scatter_geo(
regular_data,
locations="iso_alpha",
size="count",
hover_name="country_name",
custom_data=["count", "code_2"],
projection="orthographic",
)
# Add special patent locations with lat/lon
if special_data:
fig.add_trace(px.scatter_geo(
special_data,
lat="lat",
lon="lon",
size="count",
hover_name="country_name",
custom_data=["count", "code_2"],
).data[0])
# Change colour to preference.
fig.update_traces(
marker=dict(color='red'),
hovertemplate="<b>%{hovertext}</b><br>Brevets: %{customdata[0]}<extra></extra>"
)
fig.update_layout(
title="Répartition géographique des brevets similaires",
title_x=0.5,
paper_bgcolor='rgba(0,0,0,0)',
plot_bgcolor='rgba(0,0,0,0)',
margin=dict(l=0, r=0, t=40, b=0),
height=500
)
# Change colour of sea
fig.update_geos(
bgcolor='rgba(0,0,0,0)',
showocean=True,
oceancolor="lightblue",
lakecolor="lightblue"
)
return fig
# --- Business Logic ---
def read_text_file(filepath: str) -> str:
"""Reads the content of a text file."""
try:
with open(filepath, 'r', encoding='utf-8') as file:
return file.read()
except Exception as e:
logging.error(f"Error reading file {filepath}: {e}")
raise
def initialize_client() -> OpenAI:
"""Initializes the OpenAI client."""
return OpenAI()
# Load prompt templates at startup
try:
script_dir = os.path.dirname(os.path.abspath(__file__))
query_prompt_template = read_text_file(os.path.join(script_dir, "prompts", "rewrite_description_prompt_template.txt"))
mcp_prompt_template = read_text_file(os.path.join(script_dir, "prompts", "mcp_prompt_template.txt"))
except Exception as e:
print(f"CRITICAL ERROR: Could not load prompt files. Error: {e}")
query_prompt_template = "User description: {user_description}"
mcp_prompt_template = "Product description: {product_description}"
# --- Pre-calculated example data ---
EXAMPLE_RESULTS = {
"A coffee mug with a carbon handle that doesn't burn your hand and includes a cooling mechanism.": {
"rewritten_query": "An insulated coffee cup comprising a beverage-containing body with an integrated cooling mechanism and an ergonomically shaped carbon composite handle. The primary purpose of this product is to allow users to hold and drink hot beverages without discomfort or risk of burns, while simultaneously reducing the temperature of the liquid to an optimal drinking level. The cup body is constructed of a thermally stable material such as ceramic or stainless steel and features a double-walled structure that accommodates an internal cooling module within its walls. The carbon fiber handle is mechanically attached to the cup body and provides high thermal resistance, ensuring the handle remains at ambient temperature even when filled with boiling liquid. The cooling mechanism consists of a heat-absorbing element embedded between the inner and outer walls of the cup, designed to draw heat away from the beverage and dissipate it through the external surface without requiring external power. The cup operates by transferring heat from the liquid into the cooling element, maintaining the beverage at a drinkable temperature and preventing heat transfer to the handle. Unique features include the combination of a non-conductive carbon fiber handle with an integrated cooling chamber, distinguishing it from standard insulated cups. Alternate embodiments may vary cup volumes, shapes or placements of the cooling element, and materials for the cup body. The design is intended for consumer beverage use in domestic or office environments, targeting individuals who seek enhanced comfort and controlled beverage temperature.",
"strengths": [
"Integrated passive thermal management maintains optimal beverage temperature without external accessories",
"Carbon fiber composite handle ensures handle remains cool and ergonomically safe",
"Versatile choice of materials (ceramic, stainless steel, or high-performance plastic) and modular cooling elements allows adaptability to various user needs"
],
"weaknesses": [
"Increased manufacturing complexity and cost due to multilayer construction and specialized materials",
"Potential for sealing failures or leaks between walls, especially around handle junctions",
"Added weight from cooling elements or thermoelectric modules may reduce portability"
],
"rating": {"novelty": 6, "inventive_step": 5, "utility": 9, "completeness": 8, "clarity": 7},
"patents": [
{"id": "US20180012345A1", "title": "Thermal management beverage container", "company_name": "ThermoTech Inc.", "date": "2018-01-05", "country": "US", "relevance": "high"},
{"id": "US20170234567B2", "title": "Insulated drinking vessel with phase-change insert", "company_name": "CoolWare LLC", "date": "2017-08-10", "country": "US", "relevance": "high"},
{"id": "EP3045678A1", "title": "Drinkware with active thermoelectric element", "company_name": "HeatCool Corp.", "date": "2016-10-12", "country": "EP", "relevance": "low"},
{"id": "US20190123456A1", "title": "Double-walled mug with gel pack insert", "company_name": "BevCool Innovations", "date": "2019-03-15", "country": "US", "relevance": "high"},
{"id": "US20150234567A1", "title": "Nonconductive handle for hot beverage container", "company_name": "SafeHandle Co.", "date": "2015-06-20", "country": "US", "relevance": "low"}
]
},
"A real-time translation system for video calls, natively integrated without a third-party app.": {
"rewritten_query": "A real-time video call translation system is natively integrated into a video conferencing platform or device to eliminate language barriers without relying on third-party applications. The system captures incoming multilingual audio streams via built-in microphones and processes them through an onboard speech recognition engine that converts spoken words into text. This text is then transmitted to an embedded neural machine translation module, which supports multiple language pairs and employs adaptive algorithms to optimize translation accuracy in live scenarios. Translated text is rendered instantly as subtitles on the user's video feed or fed into a text-to-speech synthesis engine to generate voice output in the listener's preferred language. The system is architected as modular software components—audio capture, speech-to-text, translation, text-to-speech, and user interface—running on dedicated hardware accelerators or GPU resources within the host device. This pipeline operates with sub-second latency, maintaining audio-video synchronization and preserving speaker intonation and context cues. Innovative aspects include end-to-end native integration that minimizes data transfer delays and enhances privacy by keeping all processing local to the device or secured cloud infrastructure, as well as dynamic language model adaptation based on conversational context. Alternative embodiments allow for selective subtitle display, choice of synthesized voice profiles, and support for custom terminology databases. Applicable across corporate communications, telemedicine, online education, and global customer support, the system enables seamless multilingual interactions for professionals and consumers without additional software installations.",
"strengths": [
"Seamless integration into host video-calling platform without requiring third-party apps, reducing user friction.",
"Low-latency processing via local hardware acceleration or adaptive cloud offloading ensures real-time performance.",
"On-device processing and privacy controls protect sensitive conversations by minimizing cloud exposure."
],
"weaknesses": [
"Complexity of intercepting and synchronizing media streams across diverse platforms and OS versions.",
"Highly crowded patent landscape for real-time speech translation may pose freedom-to-operate risks.",
"Substantial computational and network resources required for multi-participant, multi-language scenarios could increase costs and affect scalability."
],
"rating": {"novelty": 6, "inventive_step": 5, "utility": 9, "completeness": 7, "clarity": 6},
"patents": [
{"id": "US20170246402A1", "title": "Real-time language translation in communication sessions", "company_name": "Microsoft Corporation", "date": "2017-08-31", "country": "US", "relevance": "high"},
{"id": "US20190061915A1", "title": "Real-time translation for video conferencing", "company_name": "Google LLC", "date": "2019-01-31", "country": "US", "relevance": "high"},
{"id": "EP2742371B1", "title": "Speech recognition and translation in mobile communications", "company_name": "Qualcomm Incorporated", "date": "2015-03-04", "country": "EP", "relevance": "high"},
{"id": "US20180345367A1", "title": "Dynamic bandwidth adaptation for streaming translated media", "company_name": "Cisco Technology, Inc.", "date": "2018-11-29", "country": "US", "relevance": "low"},
{"id": "US10570587B2", "title": "On-device neural network based speech translation", "company_name": "Apple Inc.", "date": "2019-02-26", "country": "US", "relevance": "low"}
]
},
"A biodegradable food packaging made from algae that dissolves in hot water.": {
"rewritten_query": "A biodegradable food packaging material composed of algae-derived polymers that forms a flexible, water-resistant film or container designed to dissolve entirely when immersed in hot water, addressing the need for single-use packaging alternatives that generate zero solid waste. The material is produced by extracting alginate from seaweed, optionally blending with natural plasticizers or cross-linking agents to achieve desired mechanical strength and barrier properties, then cast or extruded into sheets, pouches, cups, trays, or other container shapes. When used to package dry or moist foods, the algae-based film provides comparable protection against moisture and contaminants as conventional plastics, while remaining fully edible or safely water-soluble at temperatures above 50 °C. Upon disposal, users simply immerse the empty packaging in hot water, triggering rapid dissolution of the alginate matrix and leaving no microplastic residues. This contrasts with traditional compostable plastics that require industrial facilities; here, the unique solubility profile of the algae polymer enables on-site disposal in kitchens or restaurants. Variations include adjusting film thickness, blend ratios, or additives for tailored disintegration times and mechanical properties, as well as formats for solid foods, liquids, or multi-compartment trays. Intended for food service, retail grocery, and catering industries, this solution targets restaurants, supermarkets, and eco-conscious consumers seeking a fully circular, water-dissolvable packaging option.",
"strengths": [
"Provides fully water-soluble, zero‐waste packaging that dissolves on demand without microplastics",
"Utilizes abundant, renewable seaweed alginate, reducing reliance on petrochemical plastics",
"Customizable mechanical and dissolution properties via blend ratios and additives"
],
"weaknesses": [
"Maintaining sufficient mechanical strength and barrier performance under humid or heavy‐load conditions",
"Potential higher production cost and supply chain constraints for high‐purity alginate",
"Food‐contact safety and regulatory approval hurdles for novel edible packaging materials"
],
"rating": {"novelty": 7, "inventive_step": 6, "utility": 9, "completeness": 8, "clarity": 8},
"patents": [
{"id": "US20160123456A1", "title": "Biodegradable alginate-based film for packaging", "company_name": "AlgaTech Inc.", "date": "2016-05-12", "country": "US", "relevance": "high"},
{"id": "EP2869123B1", "title": "Water-soluble seaweed-based packaging material", "company_name": "SeaPack Ltd.", "date": "2018-03-07", "country": "EP", "relevance": "high"},
{"id": "WO2017134567A1", "title": "Edible film from brown seaweed", "company_name": "Lagarde & Co.", "date": "2017-09-21", "country": "WO", "relevance": "high"},
{"id": "CN105123456A", "title": "Preparation method for alginate blended biodegradable film", "company_name": "Shanghai Cosco", "date": "2015-11-18", "country": "CN", "relevance": "low"},
{"id": "US20190098765A1", "title": "Dissolvable packaging for hot liquid containers", "company_name": "GreenWare LLC", "date": "2019-04-22", "country": "US", "relevance": "low"}
]
}
}
def analyze_patent_idea(query: str):
"""
Analyzes a product idea to assess its patentability and finds similar patents.
This main function takes a textual description of an invention, reformulates it for technical clarity,
and then uses a tool to query a patent database. It returns a structured analysis
including strengths, weaknesses, a potential assessment, and a list of relevant patents.
Args:
query (str): A description of the idea or invention to be analyzed. Should be detailed enough to be understood. For example: "A coffee mug with a carbon handle that doesn't burn your hand".
Returns:
For LLMs/Agents: The final structured result is embedded as JSON in the last status message within an HTML comment.
Look for "<!-- LLM_RESULT: {...} -->" in the final yielded status to extract the complete analysis result.
The JSON contains: strengths (list), weaknesses (list), rating (dict), patents (list), rewritten_query (str), status (str).
For Gradio Interface: Complete analysis results for all UI components.
"""
if not query:
gr.Warning("Please enter a description of your idea.")
warning_result_for_llms = {
"error": "No query provided. Please enter a description of your idea.",
"status": "halted"
}
warning_status_with_data = f"❌ **Halted.** Please provide an idea description.\n\n<!-- LLM_RESULT: {json.dumps(warning_result_for_llms, ensure_ascii=False)} -->"
yield {
step1_status: gr.Markdown(warning_status_with_data),
step2_status: gr.Markdown(""),
step3_status: gr.Markdown(""),
rewritten_query_box: gr.Textbox(value="", visible=False),
strengths_output: gr.Markdown(value=""),
weaknesses_output: gr.Markdown(value=""),
rating_output: gr.Plot(value=None),
rating_df_output: gr.DataFrame(value=None),
patents_output: gr.DataFrame(value=None),
country_map_output: gr.Plot(value=None)
}
return
# Check if it's one of the predefined examples
logging.info(f"Checking if query is example: '{query.strip()}'")
logging.info(f"Available examples: {list(EXAMPLE_RESULTS.keys())}")
if query.strip() in EXAMPLE_RESULTS:
logging.info(f"✅ Using predefined example results for: {query[:50]}...")
example_data = EXAMPLE_RESULTS[query.strip()]
# Format results for display
strengths = "\n\n".join(f"✅ **{s.strip()}**" for s in example_data["strengths"])
weaknesses = "\n\n".join(f"❌ **{w.strip()}**" for w in example_data["weaknesses"])
# Create rating objects for plotting
rating_dict = example_data["rating"]
patent_rating = SimpleNamespace(**rating_dict)
# Create radar plot and DataFrame
radar_plot = create_radar_plot(patent_rating)
rating_df = pd.DataFrame(rating_dict.items(), columns=['Criterion', 'Score (out of 10)'])
patents_df = pd.DataFrame(example_data["patents"])
# Create country map
country_map = generate_country_map(example_data["patents"])
# Result for LLMs
final_result_for_llms = {
"strengths": example_data["strengths"],
"weaknesses": example_data["weaknesses"],
"rating": rating_dict,
"patents": example_data["patents"],
"rewritten_query": example_data["rewritten_query"],
"status": "completed_example"
}
final_status_with_data = f"✅ **Step 3:** Final Report Generation (Complete - Example)\n\n<!-- LLM_RESULT: {json.dumps(final_result_for_llms, ensure_ascii=False)} -->"
# Display instant example results
yield {
step1_status: gr.Markdown("✅ **Step 1:** Query Refinement (Complete - Example)"),
step2_status: gr.Markdown("✅ **Step 2:** MCP Patent Database Search (Complete - Example)"),
step3_status: gr.Markdown(final_status_with_data),
rewritten_query_box: gr.Textbox(value=example_data["rewritten_query"], visible=True),
strengths_output: gr.Markdown(strengths),
weaknesses_output: gr.Markdown(weaknesses),
rating_output: gr.Plot(value=radar_plot),
rating_df_output: gr.DataFrame(value=rating_df),
patents_output: gr.DataFrame(value=patents_df),
country_map_output: gr.Plot(value=country_map)
}
return
try:
client = initialize_client()
# --- 1. Rewrite the query -- -
logging.info("Rewriting query...")
query_prompt = query_prompt_template.format(user_description=query)
rewrite_response = client.responses.parse(
model="o3-mini", # model switch
input=[{"role": "user", "content": query_prompt}],
text_format=RewrittenQuery
)
rewritten_query = rewrite_response.output_parsed.product_description
logging.info("Query rewritten successfully.")
# --- 2. Extract patent information with MCP ---
logging.info("Extracting patent information with MCP...")
mcp_prompt = mcp_prompt_template.format(product_description=rewritten_query)
mcp_resp = client.responses.parse(
model="o4-mini",
tools=[{
"type": "mcp",
"server_label": "patentmcp",
"server_url": "https://bbfizp-patent-mcp.hf.space/gradio_api/mcp/sse",
"allowed_tools": [],
"require_approval": "never",
}],
input=mcp_prompt,
text_format=PatentExtraction
)
result = mcp_resp.output_parsed
logging.info("Extraction completed.")
# --- 3. Format results for display ---
strengths = "\n\n".join(f"✅ **{s.strip()}**" for s in result.strengths)
weaknesses = "\n\n".join(f"❌ **{w.strip()}**" for w in result.weaknesses)
# Create radar plot instead of DataFrame
radar_plot = create_radar_plot(result.patent_rating)
rating_df = pd.DataFrame(result.patent_rating.model_dump().items(), columns=['Criterion', 'Score (out of 10)'])
patents_df = pd.DataFrame([p.model_dump() for p in result.relevant_patents])
# Create country map from patents data
patents_data = [p.model_dump() for p in result.relevant_patents]
country_map = generate_country_map(patents_data)
# Structured result for LLMs (JSON format in the last yield)
final_result_for_llms = {
"strengths": result.strengths,
"weaknesses": result.weaknesses,
"rating": result.patent_rating.model_dump(),
"patents": [p.model_dump() for p in result.relevant_patents],
"rewritten_query": rewritten_query,
"status": "completed"
}
# Final statuses with data for LLMs
final_status_with_data = f"✅ **Step 3:** Final Report Generation (Complete)\n\n<!-- LLM_RESULT: {json.dumps(final_result_for_llms, ensure_ascii=False)} -->"
# Single final yield with all results
yield {
step1_status: gr.Markdown("✅ **Step 1:** Query Refinement (Complete)"),
step2_status: gr.Markdown("✅ **Step 2:** MCP Patent Database Search (Complete)"),
step3_status: gr.Markdown(final_status_with_data),
rewritten_query_box: gr.Textbox(value=rewritten_query, visible=True),
strengths_output: gr.Markdown(strengths),
weaknesses_output: gr.Markdown(weaknesses),
rating_output: gr.Plot(value=radar_plot),
rating_df_output: gr.DataFrame(value=rating_df),
patents_output: gr.DataFrame(value=patents_df),
country_map_output: gr.Plot(value=country_map)
}
except Exception as e:
error_message = f"An unexpected error occurred during the analysis: {str(e)}"
logging.error(error_message)
gr.Error(error_message)
error_result_for_llms = {
"error": error_message,
"status": "failed"
}
error_status_with_data = f"❌ **Analysis Failed!**\n\n<!-- LLM_RESULT: {json.dumps(error_result_for_llms, ensure_ascii=False)} -->"
yield {
step1_status: gr.Markdown(error_status_with_data),
step2_status: gr.Markdown(f"❌ An error occurred. Please check logs for details."),
step3_status: gr.Markdown(""),
rewritten_query_box: gr.Textbox(value="", visible=False),
strengths_output: gr.Markdown(value=""),
weaknesses_output: gr.Markdown(value=""),
rating_output: gr.Plot(value=None),
rating_df_output: gr.DataFrame(value=None),
patents_output: gr.DataFrame(value=None),
country_map_output: gr.Plot(value=None)
}
# --- Gradio Interface ---
with gr.Blocks(theme=gr.themes.Soft(primary_hue="indigo", secondary_hue="blue"), title="AI Patent Analyzer") as app:
gr.Markdown(
"""
<div style="text-align: center; margin-bottom: 20px;">
<h1>🏆 AI Patent Analyzer 🏆</h1>
<p><strong>Transform your idea into a comprehensive patentability analysis.</strong></p>
</div>
"""
)
with gr.Row():
with gr.Column(scale=1):
gr.Markdown("### 1. Describe Your Idea")
query_input = gr.Textbox(
label="Invention Description",
placeholder="E.g., A coffee mug with a carbon handle that doesn't burn your hand...",
lines=5,
autofocus=True,
elem_id="query_input"
)
submit_button = gr.Button("🚀 Launch Analysis", variant="primary", elem_id="submit_button")
gr.Markdown("### 2. Live Analysis Feed")
with gr.Column():
step1_status = gr.Markdown("⚪ **Step 1:** Query Refinement")
step2_status = gr.Markdown("⚪ **Step 2:** MCP Patent Database Search")
step3_status = gr.Markdown("⚪ **Step 3:** Final Report Generation")
with gr.Accordion("🔎 See the AI-Refined Technical Query", open=False):
gr.Markdown("<p style='font-size:0.9rem;color:grey;'>To ensure the most accurate search, our AI reformulates your idea into a detailed technical query. This is what's sent to the patent search tool.</p>")
rewritten_query_box = gr.Textbox(label="AI-Refined Technical Query", interactive=False, lines=8, visible=False)
with gr.Column(scale=2):
gr.Markdown("### 3. Analysis Results")
with gr.Tabs():
with gr.TabItem("📈 Strengths & Weaknesses"):
with gr.Row():
strengths_output = gr.Markdown(label="Strengths")
weaknesses_output = gr.Markdown(label="Weaknesses")
with gr.TabItem("⭐ Patentability Score"):
with gr.Row():
with gr.Column(scale=2):
rating_df_output = gr.DataFrame(headers=["Criterion", "Score (out of 10)"], interactive=False)
with gr.Column(scale=3):
rating_output = gr.Plot()
with gr.TabItem("📜 Similar Existing Patents"):
patents_output = gr.DataFrame(interactive=False)
with gr.TabItem("🗺️ Geographic Distribution"):
country_map_output = gr.Plot()
def run_example(query):
"""Non-generator wrapper for examples"""
# For examples, return the final results directly
for result in analyze_patent_idea(query):
final_result = result # The last yield contains all the results
return [
final_result[step1_status],
final_result[step2_status],
final_result[step3_status],
final_result[rewritten_query_box],
final_result[strengths_output],
final_result[weaknesses_output],
final_result[rating_output],
final_result[rating_df_output],
final_result[patents_output],
final_result[country_map_output]
]
gr.Examples(
examples=[
"A coffee mug with a carbon handle that doesn't burn your hand and includes a cooling mechanism.",
"A real-time translation system for video calls, natively integrated without a third-party app.",
"A biodegradable food packaging made from algae that dissolves in hot water."
],
inputs=query_input,
outputs=[
step1_status,
step2_status,
step3_status,
rewritten_query_box,
strengths_output,
weaknesses_output,
rating_output,
rating_df_output,
patents_output,
country_map_output
],
fn=run_example,
cache_examples=True,
label="Example Ideas"
)
with gr.Accordion("How does this work?", open=False):
gr.Markdown(
"""
This application uses a multi-step AI process:
1. **Query Refinement:** Your initial idea is sent to a Large Language Model (LLM) to be reformulated into a more formal, technical description suitable for a patent search.
2. **MCP Tool Call:** The refined query is then sent via the **Model Context Protocol (MCP)** to a specialized tool. This tool analyzes the query against a patent database.
3. **Structured Analysis:** The tool returns a structured analysis, including identified strengths, weaknesses, a quantified rating of its potential, and a list of similar patents already in existence.
4. **Final Report:** The application then formats this data into the user-friendly report you see above.
"""
)
outputs_list = [
step1_status,
step2_status,
step3_status,
rewritten_query_box,
strengths_output,
weaknesses_output,
rating_output,
rating_df_output,
patents_output,
country_map_output
]
# Connect the button to the analysis function
submit_button.click(
fn=analyze_patent_idea,
inputs=query_input,
outputs=outputs_list
)
if __name__ == "__main__":
app.queue(default_concurrency_limit=10)
app.launch(mcp_server=True, share=True)