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