DrishtiSharma commited on
Commit
bb6bebd
·
verified ·
1 Parent(s): f5b73fb

Create interim.py

Browse files
Files changed (1) hide show
  1. mylab/interim.py +208 -0
mylab/interim.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import datetime
10
+ from patent_data_api import fetch_patent_data
11
+ import numpy as np
12
+
13
+ st.title("🤖 Patent Insights Consultant")
14
+
15
+ st.sidebar.write(
16
+ "This Patent Insights Consultant uses a multi-agent system to provide actionable insights and data analysis for the patent domain."
17
+ )
18
+
19
+ patent_area = st.text_input('Enter Patent Technology Area', value="Artificial Intelligence")
20
+ stakeholder = st.text_input('Enter Stakeholder', value="Patent Attorneys")
21
+ i
22
+ st.sidebar.subheader("Advanced Options")
23
+
24
+ selected_region = st.sidebar.multiselect("Select Region(s)", options=["Global", "United States", "Europe", "China", "Other"], default=["Global"])
25
+ start_date = st.sidebar.date_input("Start Date", value=datetime.date(2018, 1, 1))
26
+ end_date = st.sidebar.date_input("End Date", value=datetime.date.today())
27
+ subdomain = st.sidebar.text_input("Enter Technology Subdomain", value="Deep Learning")
28
+
29
+ enable_advanced_analysis = st.sidebar.checkbox("Enable Advanced Analysis", value=True)
30
+ enable_custom_visualization = st.sidebar.checkbox("Enable Custom Visualizations", value=True)
31
+
32
+ enable_customization = st.sidebar.checkbox("Enable Custom Goals")
33
+ if enable_customization:
34
+ planner_goal = st.text_area(
35
+ "Planner Goal",
36
+ value="Research trends in patent filings and technological innovation, identify key players, and provide strategic recommendations."
37
+ )
38
+ writer_goal = st.text_area(
39
+ "Writer Goal",
40
+ value="Craft a professional insights document summarizing trends, strategies, and actionable outcomes for stakeholders."
41
+ )
42
+ analyst_goal = st.text_area(
43
+ "Analyst Goal",
44
+ value="Perform detailed statistical analysis of patent filings, growth trends, and innovation distribution."
45
+ )
46
+ else:
47
+ planner_goal = "Research trends in patent filings and technological innovation, identify key players, and provide strategic recommendations."
48
+ writer_goal = "Craft a professional insights document summarizing trends, strategies, and actionable outcomes for stakeholders."
49
+ analyst_goal = "Perform detailed statistical analysis of patent filings, growth trends, and innovation distribution."
50
+
51
+ llm = ChatGroq(groq_api_key=os.getenv("GROQ_API_KEY"), model="groq/llama-3.3-70b-versatile")
52
+
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
+ plan = Task(
87
+ description=(
88
+ "1. Research recent trends in {topic} patent filings and innovation.\n"
89
+ "2. Identify key players and emerging technologies.\n"
90
+ "3. Provide recommendations for stakeholders on strategic directions.\n"
91
+ "4. Limit the output to 500 words."
92
+ ),
93
+ expected_output="A research document with structured insights and strategic recommendations.",
94
+ agent=planner
95
+ )
96
+
97
+ write = Task(
98
+ description=(
99
+ "1. Use the Planner's and Analyst's outputs to craft a professional patent insights document.\n"
100
+ "2. Include key findings, visual aids, and actionable strategies.\n"
101
+ "3. Align content with stakeholder goals.\n"
102
+ "4. Limit the document to 400 words."
103
+ ),
104
+ expected_output="A polished, stakeholder-ready patent insights document.",
105
+ agent=writer
106
+ )
107
+
108
+ analyse = Task(
109
+ description=(
110
+ "1. Perform statistical analysis of patent filing trends, innovation hot spots, and growth projections.\n"
111
+ "2. Collaborate with the Planner and Writer to align on data needs.\n"
112
+ "3. Present findings in an actionable format."
113
+ ),
114
+ expected_output="A detailed statistical analysis with actionable insights for stakeholders.",
115
+ agent=analyst
116
+ )
117
+
118
+ crew = Crew(
119
+ agents=[planner, analyst, writer],
120
+ tasks=[plan, analyse, write],
121
+ verbose=True
122
+ )
123
+
124
+ def generate_pdf_report(result):
125
+ pdf = FPDF()
126
+ pdf.add_page()
127
+ pdf.set_font("Arial", size=12)
128
+ pdf.set_auto_page_break(auto=True, margin=15)
129
+
130
+ pdf.set_font("Arial", size=16, style="B")
131
+ pdf.cell(200, 10, txt="Patent Insights Report", ln=True, align="C")
132
+ pdf.ln(10)
133
+
134
+ pdf.set_font("Arial", size=12)
135
+ pdf.multi_cell(0, 10, txt=result)
136
+
137
+ report_path = "Patent_Insights_Report.pdf"
138
+ pdf.output(report_path)
139
+ return report_path
140
+
141
+ def create_visualizations(analyst_output):
142
+ if enable_custom_visualization and analyst_output:
143
+ try:
144
+ data = pd.DataFrame(analyst_output)
145
+ st.markdown("### Advanced Visualizations")
146
+
147
+ fig1 = px.scatter(data, x="Category", y="Values", title="Innovation Trends by Category", size="Impact", color="Region")
148
+ st.plotly_chart(fig1)
149
+
150
+ fig2 = px.choropleth(data, locations="Region", color="Values", title="Regional Patent Trends", locationmode="country names")
151
+ st.plotly_chart(fig2)
152
+
153
+ fig3 = px.line(data, x="Year", y="Values", color="Category", title="Yearly Patent Filing Trends")
154
+ st.plotly_chart(fig3)
155
+ except Exception as e:
156
+ st.warning(f"Failed to create visualizations: {e}")
157
+
158
+ if st.button("Generate Patent Insights"):
159
+ with st.spinner('Processing...'):
160
+ try:
161
+ start_time = time.time()
162
+
163
+ real_time_data = fetch_patent_data(
164
+ technology_area=patent_area, region=selected_region, start_date=start_date, end_date=end_date, subdomain=subdomain
165
+ )
166
+
167
+ results = crew.kickoff(inputs={"topic": patent_area, "stakeholder": stakeholder, "data": real_time_data})
168
+ elapsed_time = time.time() - start_time
169
+
170
+ st.markdown("### Final Report:")
171
+ writer_output = getattr(results.tasks_output[2], "raw", "No details available.")
172
+ if writer_output:
173
+ st.write(writer_output)
174
+ else:
175
+ st.warning("No final report available.")
176
+
177
+ with st.expander("Explore Detailed Insights"):
178
+ tab1, tab2 = st.tabs(["Planner's Insights", "Analyst's Analysis"])
179
+
180
+ with tab1:
181
+ st.markdown("### Planner's Insights")
182
+ planner_output = getattr(results.tasks_output[0], "raw", "No details available.")
183
+ st.write(planner_output)
184
+
185
+ with tab2:
186
+ st.markdown("### Analyst's Analysis")
187
+ analyst_output = getattr(results.tasks_output[1], "raw", "No details available.")
188
+ st.write(analyst_output)
189
+
190
+ if enable_advanced_analysis:
191
+ create_visualizations(analyst_output)
192
+
193
+ st.success(f"Analysis completed in {elapsed_time:.2f} seconds.")
194
+ token_usage = getattr(results, "token_usage", None)
195
+ if token_usage:
196
+ st.markdown("#### Token Usage")
197
+ st.json(token_usage)
198
+
199
+ if writer_output:
200
+ report_path = generate_pdf_report(writer_output)
201
+ with open(report_path, "rb") as report_file:
202
+ st.download_button("Download Report", data=report_file, file_name="Patent_Report.pdf")
203
+
204
+ except Exception as e:
205
+ st.error(f"An error occurred during execution: {e}")
206
+
207
+ st.sidebar.markdown("---")
208
+ st.sidebar.markdown("### Reference:")