Spaces:
Sleeping
Sleeping
DrishtiSharma
commited on
Update test.py
Browse files
test.py
CHANGED
@@ -5,28 +5,27 @@ from langchain_groq import ChatGroq
|
|
5 |
from fpdf import FPDF
|
6 |
import pandas as pd
|
7 |
import plotly.express as px
|
8 |
-
import matplotlib.pyplot as plt
|
9 |
import tempfile
|
10 |
import time
|
11 |
|
12 |
-
# Title and
|
13 |
st.title("Patent Insights Consultant")
|
14 |
-
|
15 |
st.sidebar.write(
|
16 |
"This Patent Insights Consultant uses a multi-agent system to provide actionable insights and data analysis for the patent domain."
|
17 |
)
|
18 |
|
19 |
-
# User
|
|
|
20 |
patent_area = st.text_input('Enter Patent Technology Area', value="Transparent Antennas for Windshields")
|
21 |
stakeholder = st.text_input('Enter Stakeholder', value="Patent Attorneys")
|
22 |
|
23 |
# Advanced Options
|
24 |
-
st.sidebar.
|
25 |
enable_advanced_analysis = st.sidebar.checkbox("Enable Advanced Analysis", value=True)
|
26 |
enable_custom_visualization = st.sidebar.checkbox("Enable Custom Visualizations", value=True)
|
27 |
|
28 |
-
#
|
29 |
-
st.sidebar.
|
30 |
with st.sidebar.expander("Customize Agent Goals", expanded=False):
|
31 |
enable_customization = st.checkbox("Enable Custom Goals")
|
32 |
if enable_customization:
|
@@ -47,15 +46,10 @@ with st.sidebar.expander("Customize Agent Goals", expanded=False):
|
|
47 |
writer_goal = "Craft a professional insights document summarizing trends, strategies, and actionable outcomes for stakeholders."
|
48 |
analyst_goal = "Perform detailed statistical analysis of patent filings, growth trends, and innovation distribution."
|
49 |
|
50 |
-
|
51 |
-
# LLM Object
|
52 |
-
#=================
|
53 |
llm = ChatGroq(groq_api_key=os.getenv("GROQ_API_KEY"), model="groq/llama-3.3-70b-versatile")
|
54 |
|
55 |
-
|
56 |
-
# Crew Agents
|
57 |
-
#=================
|
58 |
-
|
59 |
planner = Agent(
|
60 |
role="Patent Research Consultant",
|
61 |
goal=planner_goal,
|
@@ -89,10 +83,7 @@ analyst = Agent(
|
|
89 |
llm=llm
|
90 |
)
|
91 |
|
92 |
-
|
93 |
-
# Crew Tasks
|
94 |
-
#=================
|
95 |
-
|
96 |
plan = Task(
|
97 |
description=(
|
98 |
"1. Research recent trends in {topic} patent filings and innovation.\n"
|
@@ -131,86 +122,84 @@ crew = Crew(
|
|
131 |
verbose=True
|
132 |
)
|
133 |
|
134 |
-
|
135 |
-
|
|
|
136 |
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as temp_pdf:
|
137 |
pdf = FPDF()
|
138 |
pdf.add_page()
|
139 |
pdf.set_font("Arial", size=12)
|
140 |
pdf.set_auto_page_break(auto=True, margin=15)
|
141 |
|
142 |
-
# Title
|
143 |
pdf.set_font("Arial", size=16, style="B")
|
144 |
pdf.cell(200, 10, txt="Patent Insights Report", ln=True, align="C")
|
145 |
pdf.ln(10)
|
146 |
|
147 |
-
|
|
|
|
|
|
|
|
|
148 |
pdf.set_font("Arial", size=12)
|
149 |
pdf.multi_cell(0, 10, txt=result)
|
150 |
|
151 |
-
# Add charts if provided
|
152 |
if charts:
|
153 |
for chart_path in charts:
|
154 |
pdf.add_page()
|
155 |
pdf.image(chart_path, x=10, y=20, w=180)
|
156 |
|
157 |
-
# Add tables if provided
|
158 |
if table_data:
|
159 |
pdf.add_page()
|
160 |
pdf.set_font("Arial", size=10)
|
161 |
for row in table_data:
|
162 |
pdf.cell(200, 10, txt=str(row), ln=True)
|
163 |
|
164 |
-
# Save PDF
|
165 |
pdf.output(temp_pdf.name)
|
166 |
return temp_pdf.name
|
167 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
168 |
def create_visualizations(analyst_output):
|
169 |
-
"""Create visualizations for advanced insights."""
|
170 |
chart_paths = []
|
171 |
-
|
|
|
|
|
172 |
try:
|
173 |
-
|
174 |
-
st.
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
data = pd.DataFrame(analyst_output)
|
179 |
-
if 'Category' in data.columns and 'Values' in data.columns:
|
180 |
-
st.markdown("### Advanced Visualization")
|
181 |
-
|
182 |
-
# Create a bar chart
|
183 |
-
fig = px.bar(data, x="Category", y="Values", title="Patent Trends by Category")
|
184 |
-
st.plotly_chart(fig)
|
185 |
-
|
186 |
-
# Save chart to a file for embedding in PDF
|
187 |
-
with tempfile.NamedTemporaryFile(delete=False, suffix=".png") as temp_chart:
|
188 |
-
fig.write_image(temp_chart.name)
|
189 |
-
chart_paths.append(temp_chart.name)
|
190 |
-
else:
|
191 |
-
st.warning("Data does not have the required columns 'Category' and 'Values'.")
|
192 |
-
else:
|
193 |
-
st.warning("Analyst output is not in the correct format for visualization.")
|
194 |
except Exception as e:
|
195 |
-
st.error(f"
|
196 |
return chart_paths
|
197 |
|
198 |
def display_table(analyst_output):
|
199 |
-
"""Display tabular data for detailed insights."""
|
200 |
table_data = []
|
201 |
-
|
202 |
-
|
203 |
-
|
204 |
-
|
205 |
-
|
206 |
-
data = pd.DataFrame(analyst_output)
|
207 |
-
st.markdown("### Data Table")
|
208 |
-
st.dataframe(data)
|
209 |
-
table_data = data.to_dict(orient="records")
|
210 |
-
except Exception as e:
|
211 |
-
st.error(f"Failed to display table: {e}")
|
212 |
return table_data
|
213 |
|
|
|
|
|
214 |
if st.button("Generate Patent Insights"):
|
215 |
with st.spinner('Processing...'):
|
216 |
try:
|
@@ -218,50 +207,34 @@ if st.button("Generate Patent Insights"):
|
|
218 |
results = crew.kickoff(inputs={"topic": patent_area, "stakeholder": stakeholder})
|
219 |
elapsed_time = time.time() - start_time
|
220 |
|
221 |
-
# Display Final Report (Writer's Output)
|
222 |
-
st.markdown("### Final Report:")
|
223 |
writer_output = getattr(results.tasks_output[2], "raw", "No details available.")
|
224 |
if writer_output:
|
|
|
225 |
st.write(writer_output)
|
226 |
else:
|
227 |
st.warning("No final report available.")
|
228 |
|
229 |
-
# Option for Detailed Insights
|
230 |
with st.expander("Explore Detailed Insights"):
|
231 |
tab1, tab2 = st.tabs(["Planner's Insights", "Analyst's Analysis"])
|
232 |
|
233 |
-
# Planner's Output
|
234 |
with tab1:
|
235 |
-
st.markdown("### Planner's Insights")
|
236 |
planner_output = getattr(results.tasks_output[0], "raw", "No details available.")
|
237 |
st.write(planner_output)
|
238 |
|
239 |
-
# Analyst's Output
|
240 |
with tab2:
|
241 |
-
st.markdown("### Analyst's Analysis")
|
242 |
analyst_output = getattr(results.tasks_output[1], "raw", "No details available.")
|
243 |
st.write(analyst_output)
|
244 |
|
245 |
-
# Generate visualizations if enabled
|
246 |
charts = []
|
247 |
if enable_advanced_analysis:
|
248 |
charts = create_visualizations(analyst_output)
|
249 |
|
250 |
-
# Display tabular data
|
251 |
table_data = display_table(analyst_output)
|
252 |
|
253 |
-
# Display Token Usage and Execution Time
|
254 |
st.success(f"Analysis completed in {elapsed_time:.2f} seconds.")
|
255 |
-
|
256 |
-
|
257 |
-
st.
|
258 |
-
st.json(token_usage)
|
259 |
-
|
260 |
-
# Generate PDF Report
|
261 |
-
if writer_output:
|
262 |
-
pdf_path = generate_pdf_report(writer_output, charts=charts, table_data=table_data)
|
263 |
-
with open(pdf_path, "rb") as report_file:
|
264 |
-
st.download_button("Download Report", data=report_file, file_name="Patent_Report.pdf")
|
265 |
|
266 |
except Exception as e:
|
267 |
st.error(f"An error occurred during execution: {e}")
|
|
|
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 Insights Consultant")
|
|
|
13 |
st.sidebar.write(
|
14 |
"This Patent Insights Consultant uses a multi-agent system to provide actionable insights and data analysis for the patent domain."
|
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:
|
|
|
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,
|
|
|
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"
|
|
|
122 |
verbose=True
|
123 |
)
|
124 |
|
125 |
+
# PDF Report Generation
|
126 |
+
|
127 |
+
def generate_pdf_report(result, charts=None, table_data=None, metadata=None):
|
128 |
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as temp_pdf:
|
129 |
pdf = FPDF()
|
130 |
pdf.add_page()
|
131 |
pdf.set_font("Arial", size=12)
|
132 |
pdf.set_auto_page_break(auto=True, margin=15)
|
133 |
|
|
|
134 |
pdf.set_font("Arial", size=16, style="B")
|
135 |
pdf.cell(200, 10, txt="Patent Insights Report", ln=True, align="C")
|
136 |
pdf.ln(10)
|
137 |
|
138 |
+
if metadata:
|
139 |
+
pdf.set_font("Arial", size=10)
|
140 |
+
for key, value in metadata.items():
|
141 |
+
pdf.cell(200, 10, txt=f"{key}: {value}", ln=True)
|
142 |
+
|
143 |
pdf.set_font("Arial", size=12)
|
144 |
pdf.multi_cell(0, 10, txt=result)
|
145 |
|
|
|
146 |
if charts:
|
147 |
for chart_path in charts:
|
148 |
pdf.add_page()
|
149 |
pdf.image(chart_path, x=10, y=20, w=180)
|
150 |
|
|
|
151 |
if table_data:
|
152 |
pdf.add_page()
|
153 |
pdf.set_font("Arial", size=10)
|
154 |
for row in table_data:
|
155 |
pdf.cell(200, 10, txt=str(row), ln=True)
|
156 |
|
|
|
157 |
pdf.output(temp_pdf.name)
|
158 |
return temp_pdf.name
|
159 |
|
160 |
+
# Data Validation
|
161 |
+
|
162 |
+
def validate_analyst_output(analyst_output):
|
163 |
+
if not analyst_output:
|
164 |
+
st.warning("No data available for analysis.")
|
165 |
+
return None
|
166 |
+
if not isinstance(analyst_output, list) or not all(isinstance(item, dict) for item in analyst_output):
|
167 |
+
st.warning("Analyst output must be a list of dictionaries.")
|
168 |
+
return None
|
169 |
+
required_keys = {'Category', 'Values'}
|
170 |
+
if not all(required_keys.issubset(item.keys()) for item in analyst_output):
|
171 |
+
st.warning(f"Each dictionary must contain keys: {required_keys}")
|
172 |
+
return None
|
173 |
+
return analyst_output
|
174 |
+
|
175 |
+
# Visualization and Table Display
|
176 |
+
|
177 |
def create_visualizations(analyst_output):
|
|
|
178 |
chart_paths = []
|
179 |
+
validated_data = validate_analyst_output(analyst_output)
|
180 |
+
if validated_data:
|
181 |
+
data = pd.DataFrame(validated_data)
|
182 |
try:
|
183 |
+
fig = px.bar(data, x="Category", y="Values", title="Patent Trends by Category")
|
184 |
+
st.plotly_chart(fig)
|
185 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".png") as temp_chart:
|
186 |
+
fig.write_image(temp_chart.name)
|
187 |
+
chart_paths.append(temp_chart.name)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
188 |
except Exception as e:
|
189 |
+
st.error(f"Error generating visualization: {e}")
|
190 |
return chart_paths
|
191 |
|
192 |
def display_table(analyst_output):
|
|
|
193 |
table_data = []
|
194 |
+
validated_data = validate_analyst_output(analyst_output)
|
195 |
+
if validated_data:
|
196 |
+
data = pd.DataFrame(validated_data)
|
197 |
+
st.dataframe(data)
|
198 |
+
table_data = data.to_dict(orient="records")
|
|
|
|
|
|
|
|
|
|
|
|
|
199 |
return table_data
|
200 |
|
201 |
+
# Main Execution Block
|
202 |
+
|
203 |
if st.button("Generate Patent Insights"):
|
204 |
with st.spinner('Processing...'):
|
205 |
try:
|
|
|
207 |
results = crew.kickoff(inputs={"topic": patent_area, "stakeholder": stakeholder})
|
208 |
elapsed_time = time.time() - start_time
|
209 |
|
|
|
|
|
210 |
writer_output = getattr(results.tasks_output[2], "raw", "No details available.")
|
211 |
if writer_output:
|
212 |
+
st.markdown("### Final Report")
|
213 |
st.write(writer_output)
|
214 |
else:
|
215 |
st.warning("No final report available.")
|
216 |
|
|
|
217 |
with st.expander("Explore Detailed Insights"):
|
218 |
tab1, tab2 = st.tabs(["Planner's Insights", "Analyst's Analysis"])
|
219 |
|
|
|
220 |
with tab1:
|
|
|
221 |
planner_output = getattr(results.tasks_output[0], "raw", "No details available.")
|
222 |
st.write(planner_output)
|
223 |
|
|
|
224 |
with tab2:
|
|
|
225 |
analyst_output = getattr(results.tasks_output[1], "raw", "No details available.")
|
226 |
st.write(analyst_output)
|
227 |
|
|
|
228 |
charts = []
|
229 |
if enable_advanced_analysis:
|
230 |
charts = create_visualizations(analyst_output)
|
231 |
|
|
|
232 |
table_data = display_table(analyst_output)
|
233 |
|
|
|
234 |
st.success(f"Analysis completed in {elapsed_time:.2f} seconds.")
|
235 |
+
pdf_path = generate_pdf_report(writer_output, charts=charts, table_data=table_data, metadata={"Technology Area": patent_area, "Stakeholder": stakeholder})
|
236 |
+
with open(pdf_path, "rb") as report_file:
|
237 |
+
st.download_button("Download Report", data=report_file, file_name="Patent_Report.pdf")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
238 |
|
239 |
except Exception as e:
|
240 |
st.error(f"An error occurred during execution: {e}")
|