DrishtiSharma commited on
Commit
87500a8
·
verified ·
1 Parent(s): d5ee312

Create this.py

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