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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
from crewai import Agent, Task, Crew
|
| 3 |
+
import os
|
| 4 |
+
from langchain_groq import ChatGroq
|
| 5 |
+
from fpdf import FPDF
|
| 6 |
+
import pandas as pd
|
| 7 |
+
import plotly.express as px
|
| 8 |
+
import tempfile
|
| 9 |
+
import time
|
| 10 |
+
|
| 11 |
+
# Title and Application Introduction
|
| 12 |
+
st.title("Patent Strategy and Innovation Consultant")
|
| 13 |
+
st.sidebar.write(
|
| 14 |
+
"This application uses AI to provide actionable insights and comprehensive analysis for patent-related strategies."
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
# User Input Section
|
| 18 |
+
st.sidebar.header("User Inputs")
|
| 19 |
+
patent_area = st.text_input("Enter Patent Technology Area", value="Transparent Antennas for Windshields")
|
| 20 |
+
stakeholder = st.text_input("Enter Stakeholder", value="Patent Attorneys")
|
| 21 |
+
|
| 22 |
+
# Advanced Options
|
| 23 |
+
st.sidebar.header("Advanced Options")
|
| 24 |
+
enable_advanced_analysis = st.sidebar.checkbox("Enable Advanced Analysis", value=True)
|
| 25 |
+
enable_custom_visualization = st.sidebar.checkbox("Enable Custom Visualizations", value=True)
|
| 26 |
+
|
| 27 |
+
# Agent Customization
|
| 28 |
+
st.sidebar.header("Agent Customization")
|
| 29 |
+
with st.sidebar.expander("Customize Agent Goals", expanded=False):
|
| 30 |
+
enable_customization = st.checkbox("Enable Custom Goals")
|
| 31 |
+
if enable_customization:
|
| 32 |
+
planner_goal = st.text_area(
|
| 33 |
+
"Planner Goal",
|
| 34 |
+
value="Research trends in patent filings and technological innovation, identify key players, and provide strategic recommendations."
|
| 35 |
+
)
|
| 36 |
+
writer_goal = st.text_area(
|
| 37 |
+
"Writer Goal",
|
| 38 |
+
value="Craft a professional insights document summarizing trends, strategies, and actionable outcomes for stakeholders."
|
| 39 |
+
)
|
| 40 |
+
analyst_goal = st.text_area(
|
| 41 |
+
"Analyst Goal",
|
| 42 |
+
value="Perform detailed statistical analysis of patent filings, growth trends, and innovation distribution."
|
| 43 |
+
)
|
| 44 |
+
else:
|
| 45 |
+
planner_goal = "Research trends in patent filings and technological innovation, identify key players, and provide strategic recommendations."
|
| 46 |
+
writer_goal = "Craft a professional insights document summarizing trends, strategies, and actionable outcomes for stakeholders."
|
| 47 |
+
analyst_goal = "Perform detailed statistical analysis of patent filings, growth trends, and innovation distribution."
|
| 48 |
+
|
| 49 |
+
# LLM Initialization
|
| 50 |
+
llm = ChatGroq(groq_api_key=os.getenv("GROQ_API_KEY"), model="groq/llama-3.3-70b-versatile")
|
| 51 |
+
|
| 52 |
+
# Agent Definitions
|
| 53 |
+
planner = Agent(
|
| 54 |
+
role="Patent Research Consultant",
|
| 55 |
+
goal=planner_goal,
|
| 56 |
+
backstory=(
|
| 57 |
+
"You're tasked with researching {topic} patents and identifying key trends and players. Your work supports the Patent Writer and Data Analyst."
|
| 58 |
+
),
|
| 59 |
+
allow_delegation=False,
|
| 60 |
+
verbose=True,
|
| 61 |
+
llm=llm
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
writer = Agent(
|
| 65 |
+
role="Patent Insights Writer",
|
| 66 |
+
goal=writer_goal,
|
| 67 |
+
backstory=(
|
| 68 |
+
"Using the research from the Planner and data from the Analyst, craft a professional document summarizing patent insights for {stakeholder}."
|
| 69 |
+
),
|
| 70 |
+
allow_delegation=False,
|
| 71 |
+
verbose=True,
|
| 72 |
+
llm=llm
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
analyst = Agent(
|
| 76 |
+
role="Patent Data Analyst",
|
| 77 |
+
goal=analyst_goal,
|
| 78 |
+
backstory=(
|
| 79 |
+
"Analyze patent filing data and innovation trends in {topic} to provide statistical insights. Your analysis will guide the Writer's final report."
|
| 80 |
+
),
|
| 81 |
+
allow_delegation=False,
|
| 82 |
+
verbose=True,
|
| 83 |
+
llm=llm
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
# Task Definitions
|
| 87 |
+
plan = Task(
|
| 88 |
+
description=(
|
| 89 |
+
"1. Research recent trends in {topic} patent filings and innovation.\n"
|
| 90 |
+
"2. Identify key players and emerging technologies.\n"
|
| 91 |
+
"3. Provide recommendations for stakeholders on strategic directions.\n"
|
| 92 |
+
"4. Identify key statistics such as top regions, top players, and hot areas of innovation.\n"
|
| 93 |
+
"5. Limit the output to 500 words."
|
| 94 |
+
),
|
| 95 |
+
expected_output="A research document with structured insights, strategic recommendations, and key statistics.",
|
| 96 |
+
agent=planner
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
write = Task(
|
| 100 |
+
description=(
|
| 101 |
+
"1. Use the Planner's and Analyst's outputs to craft a professional patent insights document.\n"
|
| 102 |
+
"2. Include key findings, visual aids, and actionable strategies.\n"
|
| 103 |
+
"3. Suggest strategic directions and highlight untapped innovation areas.\n"
|
| 104 |
+
"4. Incorporate summarized tables for key statistics and example inventions.\n"
|
| 105 |
+
"5. Limit the document to 600 words."
|
| 106 |
+
),
|
| 107 |
+
expected_output="A polished, stakeholder-ready patent insights document with actionable recommendations.",
|
| 108 |
+
agent=writer
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
analyse = Task(
|
| 112 |
+
description=(
|
| 113 |
+
"1. Perform statistical analysis of patent filing trends, innovation hot spots, and growth projections.\n"
|
| 114 |
+
"2. Identify top regions, key players, and technology combinations.\n"
|
| 115 |
+
"3. Generate visualizations such as heatmaps and multi-line charts for trends.\n"
|
| 116 |
+
"4. Provide structured output with fields 'Category' and 'Values' for visualization.\n"
|
| 117 |
+
"5. Collaborate with the Planner and Writer to align on data needs."
|
| 118 |
+
),
|
| 119 |
+
expected_output="A detailed statistical analysis with actionable insights, heatmaps, and trends.",
|
| 120 |
+
agent=analyst
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
crew = Crew(
|
| 124 |
+
agents=[planner, analyst, writer],
|
| 125 |
+
tasks=[plan, analyse, write],
|
| 126 |
+
verbose=True
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
# PDF Report Generation
|
| 130 |
+
def generate_pdf_report(result, charts=None, table_data=None, metadata=None):
|
| 131 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as temp_pdf:
|
| 132 |
+
pdf = FPDF()
|
| 133 |
+
pdf.add_page()
|
| 134 |
+
pdf.set_font("Arial", size=12)
|
| 135 |
+
pdf.set_auto_page_break(auto=True, margin=15)
|
| 136 |
+
|
| 137 |
+
pdf.set_font("Arial", size=16, style="B")
|
| 138 |
+
pdf.cell(200, 10, txt="Patent Strategy and Innovation Report", ln=True, align="C")
|
| 139 |
+
pdf.ln(10)
|
| 140 |
+
|
| 141 |
+
if metadata:
|
| 142 |
+
pdf.set_font("Arial", size=10)
|
| 143 |
+
for key, value in metadata.items():
|
| 144 |
+
pdf.cell(200, 10, txt=f"{key}: {value}", ln=True)
|
| 145 |
+
|
| 146 |
+
pdf.set_font("Arial", size=12)
|
| 147 |
+
pdf.multi_cell(0, 10, txt=result)
|
| 148 |
+
|
| 149 |
+
if charts:
|
| 150 |
+
for chart_path in charts:
|
| 151 |
+
pdf.add_page()
|
| 152 |
+
pdf.image(chart_path, x=10, y=20, w=180)
|
| 153 |
+
|
| 154 |
+
if table_data:
|
| 155 |
+
pdf.add_page()
|
| 156 |
+
pdf.set_font("Arial", size=10)
|
| 157 |
+
for row in table_data:
|
| 158 |
+
pdf.cell(200, 10, txt=str(row), ln=True)
|
| 159 |
+
|
| 160 |
+
pdf.output(temp_pdf.name)
|
| 161 |
+
return temp_pdf.name
|
| 162 |
+
|
| 163 |
+
# Data Validation
|
| 164 |
+
def validate_analyst_output(analyst_output):
|
| 165 |
+
if not analyst_output:
|
| 166 |
+
st.warning("No data available for analysis.")
|
| 167 |
+
return None
|
| 168 |
+
if not isinstance(analyst_output, list) or not all(isinstance(item, dict) for item in analyst_output):
|
| 169 |
+
st.warning("Analyst output must be a list of dictionaries.")
|
| 170 |
+
return None
|
| 171 |
+
required_keys = {'Category', 'Values'}
|
| 172 |
+
if not all(required_keys.issubset(item.keys()) for item in analyst_output):
|
| 173 |
+
st.warning(f"Each dictionary must contain keys: {required_keys}")
|
| 174 |
+
return None
|
| 175 |
+
return analyst_output
|
| 176 |
+
|
| 177 |
+
# Visualization and Table Display
|
| 178 |
+
def create_visualizations(analyst_output):
|
| 179 |
+
chart_paths = []
|
| 180 |
+
validated_data = validate_analyst_output(analyst_output)
|
| 181 |
+
if validated_data:
|
| 182 |
+
data = pd.DataFrame(validated_data)
|
| 183 |
+
try:
|
| 184 |
+
bar_chart = px.bar(data, x="Category", y="Values", title="Patent Trends by Category")
|
| 185 |
+
st.plotly_chart(bar_chart)
|
| 186 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".png") as temp_chart:
|
| 187 |
+
bar_chart.write_image(temp_chart.name)
|
| 188 |
+
chart_paths.append(temp_chart.name)
|
| 189 |
+
|
| 190 |
+
pie_chart = px.pie(data, names="Category", values="Values", title="Category Distribution")
|
| 191 |
+
st.plotly_chart(pie_chart)
|
| 192 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".png") as temp_chart:
|
| 193 |
+
pie_chart.write_image(temp_chart.name)
|
| 194 |
+
chart_paths.append(temp_chart.name)
|
| 195 |
+
|
| 196 |
+
heatmap_chart = px.density_heatmap(data, x="Category", y="Values", title="Regional Patent Density")
|
| 197 |
+
st.plotly_chart(heatmap_chart)
|
| 198 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".png") as temp_chart:
|
| 199 |
+
heatmap_chart.write_image(temp_chart.name)
|
| 200 |
+
chart_paths.append(temp_chart.name)
|
| 201 |
+
|
| 202 |
+
except Exception as e:
|
| 203 |
+
st.error(f"Error generating visualization: {e}")
|
| 204 |
+
return chart_paths
|
| 205 |
+
|
| 206 |
+
def display_table(analyst_output):
|
| 207 |
+
table_data = []
|
| 208 |
+
validated_data = validate_analyst_output(analyst_output)
|
| 209 |
+
if validated_data:
|
| 210 |
+
data = pd.DataFrame(validated_data)
|
| 211 |
+
st.dataframe(data)
|
| 212 |
+
table_data = data.to_dict(orient="records")
|
| 213 |
+
return table_data
|
| 214 |
+
|
| 215 |
+
# Main Execution Block
|
| 216 |
+
if st.button("Generate Patent Insights"):
|
| 217 |
+
with st.spinner('Processing...'):
|
| 218 |
+
try:
|
| 219 |
+
start_time = time.time()
|
| 220 |
+
results = crew.kickoff(inputs={"topic": patent_area, "stakeholder": stakeholder})
|
| 221 |
+
elapsed_time = time.time() - start_time
|
| 222 |
+
|
| 223 |
+
writer_output = getattr(results.tasks_output[2], "raw", "No details available.")
|
| 224 |
+
if writer_output:
|
| 225 |
+
st.markdown("### Final Report")
|
| 226 |
+
st.write(writer_output)
|
| 227 |
+
else:
|
| 228 |
+
st.warning("No final report available.")
|
| 229 |
+
|
| 230 |
+
with st.expander("Explore Detailed Insights"):
|
| 231 |
+
tab1, tab2 = st.tabs(["Planner's Insights", "Analyst's Analysis"])
|
| 232 |
+
|
| 233 |
+
with tab1:
|
| 234 |
+
planner_output = getattr(results.tasks_output[0], "raw", "No details available.")
|
| 235 |
+
st.write(planner_output)
|
| 236 |
+
|
| 237 |
+
with tab2:
|
| 238 |
+
analyst_output = getattr(results.tasks_output[1], "raw", "No details available.")
|
| 239 |
+
st.write(analyst_output)
|
| 240 |
+
|
| 241 |
+
charts = []
|
| 242 |
+
if enable_advanced_analysis:
|
| 243 |
+
charts = create_visualizations(analyst_output)
|
| 244 |
+
|
| 245 |
+
table_data = display_table(analyst_output)
|
| 246 |
+
|
| 247 |
+
st.success(f"Analysis completed in {elapsed_time:.2f} seconds.")
|
| 248 |
+
pdf_path = generate_pdf_report(writer_output, charts=charts, table_data=table_data, metadata={"Technology Area": patent_area, "Stakeholder": stakeholder})
|
| 249 |
+
with open(pdf_path, "rb") as report_file:
|
| 250 |
+
st.download_button("Download Report", data=report_file, file_name="Patent_Strategy_Report.pdf")
|
| 251 |
+
|
| 252 |
+
except Exception as e:
|
| 253 |
+
st.error(f"An error occurred during execution: {e}")
|