DrishtiSharma commited on
Commit
be67517
·
verified ·
1 Parent(s): 9d9e7d0

Create nice_transparent_antennas.py

Browse files
sample_outputs/transparent_antennas/nice_transparent_antennas.py ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 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:
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. Limit the output to 500 words."
93
+ ),
94
+ expected_output="A research document with structured insights and strategic recommendations.",
95
+ agent=planner
96
+ )
97
+
98
+ write = Task(
99
+ description=(
100
+ "1. Use the Planner's and Analyst's outputs to craft a professional patent insights document.\n"
101
+ "2. Include key findings, visual aids, and actionable strategies.\n"
102
+ "3. Align content with stakeholder goals.\n"
103
+ "4. Limit the document to 400 words."
104
+ ),
105
+ expected_output="A polished, stakeholder-ready patent insights document.",
106
+ agent=writer
107
+ )
108
+
109
+ analyse = Task(
110
+ description=(
111
+ "1. Perform statistical analysis of patent filing trends, innovation hot spots, and growth projections.\n"
112
+ "2. Provide structured output with fields 'Category' and 'Values' for visualization.\n"
113
+ "3. Collaborate with the Planner and Writer to align on data needs."
114
+ ),
115
+ expected_output="A detailed statistical analysis with actionable insights for stakeholders.",
116
+ agent=analyst
117
+ )
118
+
119
+ crew = Crew(
120
+ agents=[planner, analyst, writer],
121
+ tasks=[plan, analyse, write],
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:
206
+ start_time = time.time()
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}")