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