DrishtiSharma commited on
Commit
351a203
·
verified ·
1 Parent(s): 030db74

Create best1.py

Browse files
Files changed (1) hide show
  1. mylab/best/best1.py +213 -0
mylab/best/best1.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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=True,
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=True,
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=True,
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=True
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
+ st.markdown("### Advanced Visualization")
159
+ fig = px.bar(data, x="Category", y="Values", title="Patent Trends by Category")
160
+ st.plotly_chart(fig)
161
+ except Exception as e:
162
+ st.warning(f"Failed to create visualizations: {e}")
163
+
164
+ if st.button("Generate Patent Insights"):
165
+ with st.spinner('Processing...'):
166
+ try:
167
+ start_time = time.time()
168
+ results = crew.kickoff(inputs={"topic": patent_area, "stakeholder": stakeholder})
169
+ elapsed_time = time.time() - start_time
170
+
171
+ # Display Final Report (Writer's Output)
172
+ st.markdown("### Final Report:")
173
+ writer_output = getattr(results.tasks_output[2], "raw", "No details available.")
174
+ if writer_output:
175
+ st.write(writer_output)
176
+ else:
177
+ st.warning("No final report available.")
178
+
179
+ # Option for Detailed Insights
180
+ with st.expander("Explore Detailed Insights"):
181
+ tab1, tab2 = st.tabs(["Planner's Insights", "Analyst's Analysis"])
182
+
183
+ # Planner's Output
184
+ with tab1:
185
+ st.markdown("### Planner's Insights")
186
+ planner_output = getattr(results.tasks_output[0], "raw", "No details available.")
187
+ st.write(planner_output)
188
+
189
+ # Analyst's Output
190
+ with tab2:
191
+ st.markdown("### Analyst's Analysis")
192
+ analyst_output = getattr(results.tasks_output[1], "raw", "No details available.")
193
+ st.write(analyst_output)
194
+
195
+ # Generate visualizations if enabled
196
+ if enable_advanced_analysis:
197
+ create_visualizations(analyst_output)
198
+
199
+ # Display Token Usage and Execution Time
200
+ st.success(f"Analysis completed in {elapsed_time:.2f} seconds.")
201
+ token_usage = getattr(results, "token_usage", None)
202
+ if token_usage:
203
+ st.markdown("#### Token Usage")
204
+ st.json(token_usage)
205
+
206
+ # Generate PDF Report
207
+ if writer_output:
208
+ report_path = generate_pdf_report(writer_output)
209
+ with open(report_path, "rb") as report_file:
210
+ st.download_button("Download Report", data=report_file, file_name="Patent_Report.pdf")
211
+
212
+ except Exception as e:
213
+ st.error(f"An error occurred during execution: {e}")