DrishtiSharma commited on
Commit
5119e1a
·
verified ·
1 Parent(s): 432a1d1

Create app3.py

Browse files
Files changed (1) hide show
  1. mylab/app3.py +201 -0
mylab/app3.py ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
12
+ st.title("🤖 Patent Insights Consultant")
13
+
14
+ st.sidebar.write(
15
+ "This Patent Insights Consultant uses a multi-agent system to provide actionable insights and data analysis for the patent domain."
16
+ )
17
+
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
+ st.sidebar.subheader("Advanced Options")
22
+
23
+ selected_region = st.sidebar.selectbox("Select Region", options=["Global", "United States", "Europe", "China", "Other"])
24
+ start_date = st.sidebar.date_input("Start Date", value=datetime.date(2018, 1, 1))
25
+ end_date = st.sidebar.date_input("End Date", value=datetime.date.today())
26
+
27
+ enable_advanced_analysis = st.sidebar.checkbox("Enable Advanced Analysis", value=True)
28
+ enable_custom_visualization = st.sidebar.checkbox("Enable Custom Visualizations", value=True)
29
+
30
+ enable_customization = st.sidebar.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 = ChatGroq(groq_api_key=os.getenv("GROQ_API_KEY"), model="groq/llama-3.3-70b-versatile")
50
+
51
+ planner = Agent(
52
+ role="Patent Research Consultant",
53
+ goal=planner_goal,
54
+ backstory=(
55
+ "You're tasked with researching {topic} patents and identifying key trends and players. Your work supports the Patent Writer and Data Analyst."
56
+ ),
57
+ allow_delegation=False,
58
+ verbose=True,
59
+ llm=llm
60
+ )
61
+
62
+ writer = Agent(
63
+ role="Patent Insights Writer",
64
+ goal=writer_goal,
65
+ backstory=(
66
+ "Using the research from the Planner and data from the Analyst, craft a professional document summarizing patent insights for {stakeholder}."
67
+ ),
68
+ allow_delegation=False,
69
+ verbose=True,
70
+ llm=llm
71
+ )
72
+
73
+ analyst = Agent(
74
+ role="Patent Data Analyst",
75
+ goal=analyst_goal,
76
+ backstory=(
77
+ "Analyze patent filing data and innovation trends in {topic} to provide statistical insights. Your analysis will guide the Writer's final report."
78
+ ),
79
+ allow_delegation=False,
80
+ verbose=True,
81
+ llm=llm
82
+ )
83
+
84
+ plan = Task(
85
+ description=(
86
+ "1. Research recent trends in {topic} patent filings and innovation.\n"
87
+ "2. Identify key players and emerging technologies.\n"
88
+ "3. Provide recommendations for stakeholders on strategic directions.\n"
89
+ "4. Limit the output to 500 words."
90
+ ),
91
+ expected_output="A research document with structured insights and strategic recommendations.",
92
+ agent=planner
93
+ )
94
+
95
+ write = Task(
96
+ description=(
97
+ "1. Use the Planner's and Analyst's outputs to craft a professional patent insights document.\n"
98
+ "2. Include key findings, visual aids, and actionable strategies.\n"
99
+ "3. Align content with stakeholder goals.\n"
100
+ "4. Limit the document to 400 words."
101
+ ),
102
+ expected_output="A polished, stakeholder-ready patent insights document.",
103
+ agent=writer
104
+ )
105
+
106
+ analyse = Task(
107
+ description=(
108
+ "1. Perform statistical analysis of patent filing trends, innovation hot spots, and growth projections.\n"
109
+ "2. Collaborate with the Planner and Writer to align on data needs.\n"
110
+ "3. Present findings in an actionable format."
111
+ ),
112
+ expected_output="A detailed statistical analysis with actionable insights for stakeholders.",
113
+ agent=analyst
114
+ )
115
+
116
+ crew = Crew(
117
+ agents=[planner, analyst, writer],
118
+ tasks=[plan, analyse, write],
119
+ verbose=True
120
+ )
121
+
122
+ def generate_pdf_report(result):
123
+ pdf = FPDF()
124
+ pdf.add_page()
125
+ pdf.set_font("Arial", size=12)
126
+ pdf.set_auto_page_break(auto=True, margin=15)
127
+
128
+ pdf.set_font("Arial", size=16, style="B")
129
+ pdf.cell(200, 10, txt="Patent Insights Report", ln=True, align="C")
130
+ pdf.ln(10)
131
+
132
+ pdf.set_font("Arial", size=12)
133
+ pdf.multi_cell(0, 10, txt=result)
134
+
135
+ report_path = "Patent_Insights_Report.pdf"
136
+ pdf.output(report_path)
137
+ return report_path
138
+
139
+ def create_visualizations(analyst_output):
140
+ if enable_custom_visualization and analyst_output:
141
+ try:
142
+ data = pd.DataFrame(analyst_output)
143
+ st.markdown("### Advanced Visualization")
144
+
145
+ fig = px.scatter(data, x="Category", y="Values", title="Innovation Trends by Category", size="Impact", color="Region")
146
+ st.plotly_chart(fig)
147
+ except Exception as e:
148
+ st.warning(f"Failed to create visualizations: {e}")
149
+
150
+ if st.button("Generate Patent Insights"):
151
+ with st.spinner('Processing...'):
152
+ try:
153
+ start_time = time.time()
154
+
155
+ real_time_data = fetch_patent_data(
156
+ technology_area=patent_area, region=selected_region, start_date=start_date, end_date=end_date
157
+ )
158
+
159
+ results = crew.kickoff(inputs={"topic": patent_area, "stakeholder": stakeholder, "data": real_time_data})
160
+ elapsed_time = time.time() - start_time
161
+
162
+ st.markdown("### Final Report:")
163
+ writer_output = getattr(results.tasks_output[2], "raw", "No details available.")
164
+ if writer_output:
165
+ st.write(writer_output)
166
+ else:
167
+ st.warning("No final report available.")
168
+
169
+ with st.expander("Explore Detailed Insights"):
170
+ tab1, tab2 = st.tabs(["Planner's Insights", "Analyst's Analysis"])
171
+
172
+ with tab1:
173
+ st.markdown("### Planner's Insights")
174
+ planner_output = getattr(results.tasks_output[0], "raw", "No details available.")
175
+ st.write(planner_output)
176
+
177
+ with tab2:
178
+ st.markdown("### Analyst's Analysis")
179
+ analyst_output = getattr(results.tasks_output[1], "raw", "No details available.")
180
+ st.write(analyst_output)
181
+
182
+ if enable_advanced_analysis:
183
+ create_visualizations(analyst_output)
184
+
185
+ st.success(f"Analysis completed in {elapsed_time:.2f} seconds.")
186
+ token_usage = getattr(results, "token_usage", None)
187
+ if token_usage:
188
+ st.markdown("#### Token Usage")
189
+ st.json(token_usage)
190
+
191
+ if writer_output:
192
+ report_path = generate_pdf_report(writer_output)
193
+ with open(report_path, "rb") as report_file:
194
+ st.download_button("Download Report", data=report_file, file_name="Patent_Report.pdf")
195
+
196
+ except Exception as e:
197
+ st.error(f"An error occurred during execution: {e}")
198
+
199
+ st.sidebar.markdown("---")
200
+ st.sidebar.markdown("### Reference:")
201
+ st.sidebar.markdown("[Multi-Agent Patent Consultant](https://example.com)")