DrishtiSharma commited on
Commit
9947f9a
·
verified ·
1 Parent(s): 81de503

Create mylab/app1.py

Browse files
Files changed (1) hide show
  1. mylab/app1.py +226 -0
mylab/app1.py ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 time
9
+
10
+ # Title and Sidebar
11
+ st.title("🤖 Patent Insights Consultant")
12
+
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 Inputs
18
+ patent_area = st.text_input('Enter Patent Technology Area', value="Artificial Intelligence")
19
+ stakeholder = st.text_input('Enter Stakeholder', value="Patent Attorneys")
20
+
21
+ # Advanced Options
22
+ st.sidebar.subheader("Advanced Options")
23
+
24
+ # Enable/Disable Advanced Features
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
+
31
+ # Display customization section in a collapsible expander
32
+ with st.sidebar.expander("Customize Agent Goals", expanded=False):
33
+ enable_customization = st.checkbox("Enable Custom Goals")
34
+ if enable_customization:
35
+ planner_goal = st.text_area(
36
+ "Planner Goal",
37
+ value="Research trends in patent filings and technological innovation, identify key players, and provide strategic recommendations."
38
+ )
39
+ writer_goal = st.text_area(
40
+ "Writer Goal",
41
+ value="Craft a professional insights document summarizing trends, strategies, and actionable outcomes for stakeholders."
42
+ )
43
+ analyst_goal = st.text_area(
44
+ "Analyst Goal",
45
+ value="Perform detailed statistical analysis of patent filings, growth trends, and innovation distribution."
46
+ )
47
+ else:
48
+ planner_goal = "Research trends in patent filings and technological innovation, identify key players, and provide strategic recommendations."
49
+ writer_goal = "Craft a professional insights document summarizing trends, strategies, and actionable outcomes for stakeholders."
50
+ analyst_goal = "Perform detailed statistical analysis of patent filings, growth trends, and innovation distribution."
51
+
52
+ #=================
53
+ # LLM Object
54
+ #=================
55
+ llm = ChatGroq(groq_api_key=os.getenv("GROQ_API_KEY"), model="groq/llama-3.3-70b-versatile")
56
+
57
+ #=================
58
+ # Crew Agents
59
+ #=================
60
+
61
+ planner = Agent(
62
+ role="Patent Research Consultant",
63
+ goal=planner_goal,
64
+ backstory=(
65
+ "You're tasked with researching {topic} patents and identifying key trends and players. Your work supports the Patent Writer and Data Analyst."
66
+ ),
67
+ allow_delegation=False,
68
+ verbose=True,
69
+ llm=llm
70
+ )
71
+
72
+ writer = Agent(
73
+ role="Patent Insights Writer",
74
+ goal=writer_goal,
75
+ backstory=(
76
+ "Using the research from the Planner and data from the Analyst, craft a professional document summarizing patent insights for {stakeholder}."
77
+ ),
78
+ allow_delegation=False,
79
+ verbose=True,
80
+ llm=llm
81
+ )
82
+
83
+ analyst = Agent(
84
+ role="Patent Data Analyst",
85
+ goal=analyst_goal,
86
+ backstory=(
87
+ "Analyze patent filing data and innovation trends in {topic} to provide statistical insights. Your analysis will guide the Writer's final report."
88
+ ),
89
+ allow_delegation=False,
90
+ verbose=True,
91
+ llm=llm
92
+ )
93
+
94
+ #=================
95
+ # Crew Tasks
96
+ #=================
97
+
98
+ plan = Task(
99
+ description=(
100
+ "1. Research recent trends in {topic} patent filings and innovation.\n"
101
+ "2. Identify key players and emerging technologies.\n"
102
+ "3. Provide recommendations for stakeholders on strategic directions.\n"
103
+ "4. Limit the output to 500 words."
104
+ ),
105
+ expected_output="A research document with structured insights and strategic recommendations.",
106
+ agent=planner
107
+ )
108
+
109
+ write = Task(
110
+ description=(
111
+ "1. Use the Planner's and Analyst's outputs to craft a professional patent insights document.\n"
112
+ "2. Include key findings, visual aids, and actionable strategies.\n"
113
+ "3. Align content with stakeholder goals.\n"
114
+ "4. Limit the document to 400 words."
115
+ ),
116
+ expected_output="A polished, stakeholder-ready patent insights document.",
117
+ agent=writer
118
+ )
119
+
120
+ analyse = Task(
121
+ description=(
122
+ "1. Perform statistical analysis of patent filing trends, innovation hot spots, and growth projections.\n"
123
+ "2. Collaborate with the Planner and Writer to align on data needs.\n"
124
+ "3. Present findings in an actionable format."
125
+ ),
126
+ expected_output="A detailed statistical analysis with actionable insights for stakeholders.",
127
+ agent=analyst
128
+ )
129
+
130
+ #=================
131
+ # Execution
132
+ #=================
133
+
134
+ crew = Crew(
135
+ agents=[planner, analyst, writer],
136
+ tasks=[plan, analyse, write],
137
+ verbose=True
138
+ )
139
+
140
+ def generate_pdf_report(result):
141
+ """Generate a professional PDF report from the Crew output."""
142
+ pdf = FPDF()
143
+ pdf.add_page()
144
+ pdf.set_font("Arial", size=12)
145
+ pdf.set_auto_page_break(auto=True, margin=15)
146
+
147
+ # Title
148
+ pdf.set_font("Arial", size=16, style="B")
149
+ pdf.cell(200, 10, txt="Patent Insights Report", ln=True, align="C")
150
+ pdf.ln(10)
151
+
152
+ # Content
153
+ pdf.set_font("Arial", size=12)
154
+ pdf.multi_cell(0, 10, txt=result)
155
+
156
+ # Save PDF
157
+ report_path = "Patent_Insights_Report.pdf"
158
+ pdf.output(report_path)
159
+ return report_path
160
+
161
+ def create_visualizations(analyst_output):
162
+ """Create visualizations for advanced insights."""
163
+ if enable_custom_visualization and analyst_output:
164
+ try:
165
+ data = pd.DataFrame(analyst_output)
166
+ st.markdown("### Advanced Visualization")
167
+
168
+ fig = px.bar(data, x="Category", y="Values", title="Patent Trends by Category")
169
+ st.plotly_chart(fig)
170
+ except Exception as e:
171
+ st.warning(f"Failed to create visualizations: {e}")
172
+
173
+ if st.button("Generate Patent Insights"):
174
+ with st.spinner('Processing...'):
175
+ try:
176
+ start_time = time.time()
177
+ results = crew.kickoff(inputs={"topic": patent_area, "stakeholder": stakeholder})
178
+ elapsed_time = time.time() - start_time
179
+
180
+ # Display Final Report (Writer's Output)
181
+ st.markdown("### Final Report:")
182
+ writer_output = getattr(results.tasks_output[2], "raw", "No details available.")
183
+ if writer_output:
184
+ st.write(writer_output)
185
+ else:
186
+ st.warning("No final report available.")
187
+
188
+ # Option for Detailed Insights
189
+ with st.expander("Explore Detailed Insights"):
190
+ tab1, tab2 = st.tabs(["Planner's Insights", "Analyst's Analysis"])
191
+
192
+ # Planner's Output
193
+ with tab1:
194
+ st.markdown("### Planner's Insights")
195
+ planner_output = getattr(results.tasks_output[0], "raw", "No details available.")
196
+ st.write(planner_output)
197
+
198
+ # Analyst's Output
199
+ with tab2:
200
+ st.markdown("### Analyst's Analysis")
201
+ analyst_output = getattr(results.tasks_output[1], "raw", "No details available.")
202
+ st.write(analyst_output)
203
+
204
+ # Generate visualizations if enabled
205
+ if enable_advanced_analysis:
206
+ create_visualizations(analyst_output)
207
+
208
+ # Display Token Usage and Execution Time
209
+ st.success(f"Analysis completed in {elapsed_time:.2f} seconds.")
210
+ token_usage = getattr(results, "token_usage", None)
211
+ if token_usage:
212
+ st.markdown("#### Token Usage")
213
+ st.json(token_usage)
214
+
215
+ # Generate PDF Report
216
+ if writer_output:
217
+ report_path = generate_pdf_report(writer_output)
218
+ with open(report_path, "rb") as report_file:
219
+ st.download_button("Download Report", data=report_file, file_name="Patent_Report.pdf")
220
+
221
+ except Exception as e:
222
+ st.error(f"An error occurred during execution: {e}")
223
+
224
+ # Add reference and credits in the sidebar
225
+ st.sidebar.markdown("---")
226
+ st.sidebar.markdown("### Reference:")