DrishtiSharma commited on
Commit
4f3cf84
·
verified ·
1 Parent(s): d6a3a4c

Create best77.py

Browse files
Files changed (1) hide show
  1. mylab/best/best77.py +243 -0
mylab/best/best77.py ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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. 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
+ def generate_pdf_report(result, charts=None, table_data=None, metadata=None):
127
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as temp_pdf:
128
+ pdf = FPDF()
129
+ pdf.add_page()
130
+ pdf.set_font("Arial", size=12)
131
+ pdf.set_auto_page_break(auto=True, margin=15)
132
+
133
+ pdf.set_font("Arial", size=16, style="B")
134
+ pdf.cell(200, 10, txt="Patent Strategy and Innovation Report", ln=True, align="C")
135
+ pdf.ln(10)
136
+
137
+ if metadata:
138
+ pdf.set_font("Arial", size=10)
139
+ for key, value in metadata.items():
140
+ pdf.cell(200, 10, txt=f"{key}: {value}", ln=True)
141
+
142
+ pdf.set_font("Arial", size=12)
143
+ pdf.multi_cell(0, 10, txt=result)
144
+
145
+ if charts:
146
+ for chart_path in charts:
147
+ pdf.add_page()
148
+ pdf.image(chart_path, x=10, y=20, w=180)
149
+
150
+ if table_data:
151
+ pdf.add_page()
152
+ pdf.set_font("Arial", size=10)
153
+ for row in table_data:
154
+ pdf.cell(200, 10, txt=str(row), ln=True)
155
+
156
+ pdf.output(temp_pdf.name)
157
+ return temp_pdf.name
158
+
159
+ # Data Validation
160
+ def validate_analyst_output(analyst_output):
161
+ if not analyst_output:
162
+ st.warning("No data available for analysis.")
163
+ return None
164
+ if not isinstance(analyst_output, list) or not all(isinstance(item, dict) for item in analyst_output):
165
+ st.warning("Analyst output must be a list of dictionaries.")
166
+ return None
167
+ required_keys = {'Category', 'Values'}
168
+ if not all(required_keys.issubset(item.keys()) for item in analyst_output):
169
+ st.warning(f"Each dictionary must contain keys: {required_keys}")
170
+ return None
171
+ return analyst_output
172
+
173
+ # Visualization and Table Display
174
+ def create_visualizations(analyst_output):
175
+ chart_paths = []
176
+ validated_data = validate_analyst_output(analyst_output)
177
+ if validated_data:
178
+ data = pd.DataFrame(validated_data)
179
+ try:
180
+ bar_chart = px.bar(data, x="Category", y="Values", title="Patent Trends by Category")
181
+ st.plotly_chart(bar_chart)
182
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".png") as temp_chart:
183
+ bar_chart.write_image(temp_chart.name)
184
+ chart_paths.append(temp_chart.name)
185
+
186
+ pie_chart = px.pie(data, names="Category", values="Values", title="Category Distribution")
187
+ st.plotly_chart(pie_chart)
188
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".png") as temp_chart:
189
+ pie_chart.write_image(temp_chart.name)
190
+ chart_paths.append(temp_chart.name)
191
+
192
+ except Exception as e:
193
+ st.error(f"Error generating visualization: {e}")
194
+ return chart_paths
195
+
196
+ def display_table(analyst_output):
197
+ table_data = []
198
+ validated_data = validate_analyst_output(analyst_output)
199
+ if validated_data:
200
+ data = pd.DataFrame(validated_data)
201
+ st.dataframe(data)
202
+ table_data = data.to_dict(orient="records")
203
+ return table_data
204
+
205
+ # Main Execution Block
206
+ if st.button("Generate Patent Insights"):
207
+ with st.spinner('Processing...'):
208
+ try:
209
+ start_time = time.time()
210
+ results = crew.kickoff(inputs={"topic": patent_area, "stakeholder": stakeholder})
211
+ elapsed_time = time.time() - start_time
212
+
213
+ writer_output = getattr(results.tasks_output[2], "raw", "No details available.")
214
+ if writer_output:
215
+ st.markdown("### Final Report")
216
+ st.write(writer_output)
217
+ else:
218
+ st.warning("No final report available.")
219
+
220
+ with st.expander("Explore Detailed Insights"):
221
+ tab1, tab2 = st.tabs(["Planner's Insights", "Analyst's Analysis"])
222
+
223
+ with tab1:
224
+ planner_output = getattr(results.tasks_output[0], "raw", "No details available.")
225
+ st.write(planner_output)
226
+
227
+ with tab2:
228
+ analyst_output = getattr(results.tasks_output[1], "raw", "No details available.")
229
+ st.write(analyst_output)
230
+
231
+ charts = []
232
+ if enable_advanced_analysis:
233
+ charts = create_visualizations(analyst_output)
234
+
235
+ table_data = display_table(analyst_output)
236
+
237
+ st.success(f"Analysis completed in {elapsed_time:.2f} seconds.")
238
+ pdf_path = generate_pdf_report(writer_output, charts=charts, table_data=table_data, metadata={"Technology Area": patent_area, "Stakeholder": stakeholder})
239
+ with open(pdf_path, "rb") as report_file:
240
+ st.download_button("Download Report", data=report_file, file_name="Patent_Strategy_Report.pdf")
241
+
242
+ except Exception as e:
243
+ st.error(f"An error occurred during execution: {e}")