DrishtiSharma commited on
Commit
6d0184c
·
verified ·
1 Parent(s): 9964dbc

Create test.py

Browse files
Files changed (1) hide show
  1. test.py +267 -0
test.py ADDED
@@ -0,0 +1,267 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 matplotlib.pyplot as plt
9
+ import tempfile
10
+ import time
11
+
12
+ # Title and Sidebar
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 Inputs
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.subheader("Advanced Options")
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
+ # Optional Customization
29
+ st.sidebar.subheader("Agent Customization")
30
+ with st.sidebar.expander("Customize Agent Goals", expanded=False):
31
+ enable_customization = st.checkbox("Enable Custom Goals")
32
+ if enable_customization:
33
+ planner_goal = st.text_area(
34
+ "Planner Goal",
35
+ value="Research trends in patent filings and technological innovation, identify key players, and provide strategic recommendations."
36
+ )
37
+ writer_goal = st.text_area(
38
+ "Writer Goal",
39
+ value="Craft a professional insights document summarizing trends, strategies, and actionable outcomes for stakeholders."
40
+ )
41
+ analyst_goal = st.text_area(
42
+ "Analyst Goal",
43
+ value="Perform detailed statistical analysis of patent filings, growth trends, and innovation distribution."
44
+ )
45
+ else:
46
+ planner_goal = "Research trends in patent filings and technological innovation, identify key players, and provide strategic recommendations."
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,
62
+ backstory=(
63
+ "You're tasked with researching {topic} patents and identifying key trends and players. Your work supports the Patent Writer and Data Analyst."
64
+ ),
65
+ allow_delegation=False,
66
+ verbose=True,
67
+ llm=llm
68
+ )
69
+
70
+ writer = Agent(
71
+ role="Patent Insights Writer",
72
+ goal=writer_goal,
73
+ backstory=(
74
+ "Using the research from the Planner and data from the Analyst, craft a professional document summarizing patent insights for {stakeholder}."
75
+ ),
76
+ allow_delegation=False,
77
+ verbose=True,
78
+ llm=llm
79
+ )
80
+
81
+ analyst = Agent(
82
+ role="Patent Data Analyst",
83
+ goal=analyst_goal,
84
+ backstory=(
85
+ "Analyze patent filing data and innovation trends in {topic} to provide statistical insights. Your analysis will guide the Writer's final report."
86
+ ),
87
+ allow_delegation=False,
88
+ verbose=True,
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"
99
+ "2. Identify key players and emerging technologies.\n"
100
+ "3. Provide recommendations for stakeholders on strategic directions.\n"
101
+ "4. Limit the output to 500 words."
102
+ ),
103
+ expected_output="A research document with structured insights and strategic recommendations.",
104
+ agent=planner
105
+ )
106
+
107
+ write = Task(
108
+ description=(
109
+ "1. Use the Planner's and Analyst's outputs to craft a professional patent insights document.\n"
110
+ "2. Include key findings, visual aids, and actionable strategies.\n"
111
+ "3. Align content with stakeholder goals.\n"
112
+ "4. Limit the document to 400 words."
113
+ ),
114
+ expected_output="A polished, stakeholder-ready patent insights document.",
115
+ agent=writer
116
+ )
117
+
118
+ analyse = Task(
119
+ description=(
120
+ "1. Perform statistical analysis of patent filing trends, innovation hot spots, and growth projections.\n"
121
+ "2. Provide structured output with fields 'Category' and 'Values' for visualization.\n"
122
+ "3. Collaborate with the Planner and Writer to align on data needs."
123
+ ),
124
+ expected_output="A detailed statistical analysis with actionable insights for stakeholders.",
125
+ agent=analyst
126
+ )
127
+
128
+ crew = Crew(
129
+ agents=[planner, analyst, writer],
130
+ tasks=[plan, analyse, write],
131
+ verbose=True
132
+ )
133
+
134
+ def generate_pdf_report(result, charts=None, table_data=None):
135
+ """Generate a professional PDF report from the Crew output."""
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
+ # Content
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
+ if enable_custom_visualization and analyst_output:
172
+ try:
173
+ st.markdown("#### Debugging Analyst Output")
174
+ st.write(analyst_output)
175
+
176
+ # Validate and format analyst output
177
+ if isinstance(analyst_output, list) and all(isinstance(item, dict) for item in analyst_output):
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"Failed to create visualizations: {e}")
196
+ return chart_paths
197
+
198
+ def display_table(analyst_output):
199
+ """Display tabular data for detailed insights."""
200
+ table_data = []
201
+ if analyst_output and isinstance(analyst_output, list):
202
+ try:
203
+ st.markdown("#### Debugging Analyst Output for Table")
204
+ st.write(analyst_output)
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:
217
+ start_time = time.time()
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
+ token_usage = getattr(results, "token_usage", None)
256
+ if token_usage:
257
+ st.markdown("#### Token Usage")
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}")