File size: 8,153 Bytes
bb6bebd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
import streamlit as st
from crewai import Agent, Task, Crew
import os
from langchain_groq import ChatGroq
from fpdf import FPDF
import pandas as pd
import plotly.express as px
import time
import datetime
from patent_data_api import fetch_patent_data
import numpy as np

st.title("🤖 Patent Insights Consultant")

st.sidebar.write(
    "This Patent Insights Consultant uses a multi-agent system to provide actionable insights and data analysis for the patent domain."
)

patent_area = st.text_input('Enter Patent Technology Area', value="Artificial Intelligence")
stakeholder = st.text_input('Enter Stakeholder', value="Patent Attorneys")
i
st.sidebar.subheader("Advanced Options")

selected_region = st.sidebar.multiselect("Select Region(s)", options=["Global", "United States", "Europe", "China", "Other"], default=["Global"])
start_date = st.sidebar.date_input("Start Date", value=datetime.date(2018, 1, 1))
end_date = st.sidebar.date_input("End Date", value=datetime.date.today())
subdomain = st.sidebar.text_input("Enter Technology Subdomain", value="Deep Learning")

enable_advanced_analysis = st.sidebar.checkbox("Enable Advanced Analysis", value=True)
enable_custom_visualization = st.sidebar.checkbox("Enable Custom Visualizations", value=True)

enable_customization = st.sidebar.checkbox("Enable Custom Goals")
if enable_customization:
    planner_goal = st.text_area(
        "Planner Goal",
        value="Research trends in patent filings and technological innovation, identify key players, and provide strategic recommendations."
    )
    writer_goal = st.text_area(
        "Writer Goal",
        value="Craft a professional insights document summarizing trends, strategies, and actionable outcomes for stakeholders."
    )
    analyst_goal = st.text_area(
        "Analyst Goal",
        value="Perform detailed statistical analysis of patent filings, growth trends, and innovation distribution."
    )
else:
    planner_goal = "Research trends in patent filings and technological innovation, identify key players, and provide strategic recommendations."
    writer_goal = "Craft a professional insights document summarizing trends, strategies, and actionable outcomes for stakeholders."
    analyst_goal = "Perform detailed statistical analysis of patent filings, growth trends, and innovation distribution."

llm = ChatGroq(groq_api_key=os.getenv("GROQ_API_KEY"), model="groq/llama-3.3-70b-versatile")

planner = Agent(
    role="Patent Research Consultant",
    goal=planner_goal,
    backstory=(
        "You're tasked with researching {topic} patents and identifying key trends and players. Your work supports the Patent Writer and Data Analyst."
    ),
    allow_delegation=False,
    verbose=True,
    llm=llm
)

writer = Agent(
    role="Patent Insights Writer",
    goal=writer_goal,
    backstory=(
        "Using the research from the Planner and data from the Analyst, craft a professional document summarizing patent insights for {stakeholder}."
    ),
    allow_delegation=False,
    verbose=True,
    llm=llm
)

analyst = Agent(
    role="Patent Data Analyst",
    goal=analyst_goal,
    backstory=(
        "Analyze patent filing data and innovation trends in {topic} to provide statistical insights. Your analysis will guide the Writer's final report."
    ),
    allow_delegation=False,
    verbose=True,
    llm=llm
)

plan = Task(
    description=(
        "1. Research recent trends in {topic} patent filings and innovation.\n"
        "2. Identify key players and emerging technologies.\n"
        "3. Provide recommendations for stakeholders on strategic directions.\n"
        "4. Limit the output to 500 words."
    ),
    expected_output="A research document with structured insights and strategic recommendations.",
    agent=planner
)

write = Task(
    description=(
        "1. Use the Planner's and Analyst's outputs to craft a professional patent insights document.\n"
        "2. Include key findings, visual aids, and actionable strategies.\n"
        "3. Align content with stakeholder goals.\n"
        "4. Limit the document to 400 words."
    ),
    expected_output="A polished, stakeholder-ready patent insights document.",
    agent=writer
)

analyse = Task(
    description=(
        "1. Perform statistical analysis of patent filing trends, innovation hot spots, and growth projections.\n"
        "2. Collaborate with the Planner and Writer to align on data needs.\n"
        "3. Present findings in an actionable format."
    ),
    expected_output="A detailed statistical analysis with actionable insights for stakeholders.",
    agent=analyst
)

crew = Crew(
    agents=[planner, analyst, writer],
    tasks=[plan, analyse, write],
    verbose=True
)

def generate_pdf_report(result):
    pdf = FPDF()
    pdf.add_page()
    pdf.set_font("Arial", size=12)
    pdf.set_auto_page_break(auto=True, margin=15)

    pdf.set_font("Arial", size=16, style="B")
    pdf.cell(200, 10, txt="Patent Insights Report", ln=True, align="C")
    pdf.ln(10)

    pdf.set_font("Arial", size=12)
    pdf.multi_cell(0, 10, txt=result)

    report_path = "Patent_Insights_Report.pdf"
    pdf.output(report_path)
    return report_path

def create_visualizations(analyst_output):
    if enable_custom_visualization and analyst_output:
        try:
            data = pd.DataFrame(analyst_output)
            st.markdown("### Advanced Visualizations")

            fig1 = px.scatter(data, x="Category", y="Values", title="Innovation Trends by Category", size="Impact", color="Region")
            st.plotly_chart(fig1)

            fig2 = px.choropleth(data, locations="Region", color="Values", title="Regional Patent Trends", locationmode="country names")
            st.plotly_chart(fig2)

            fig3 = px.line(data, x="Year", y="Values", color="Category", title="Yearly Patent Filing Trends")
            st.plotly_chart(fig3)
        except Exception as e:
            st.warning(f"Failed to create visualizations: {e}")

if st.button("Generate Patent Insights"):
    with st.spinner('Processing...'):
        try:
            start_time = time.time()

            real_time_data = fetch_patent_data(
                technology_area=patent_area, region=selected_region, start_date=start_date, end_date=end_date, subdomain=subdomain
            )

            results = crew.kickoff(inputs={"topic": patent_area, "stakeholder": stakeholder, "data": real_time_data})
            elapsed_time = time.time() - start_time

            st.markdown("### Final Report:")
            writer_output = getattr(results.tasks_output[2], "raw", "No details available.")
            if writer_output:
                st.write(writer_output)
            else:
                st.warning("No final report available.")

            with st.expander("Explore Detailed Insights"):
                tab1, tab2 = st.tabs(["Planner's Insights", "Analyst's Analysis"])

                with tab1:
                    st.markdown("### Planner's Insights")
                    planner_output = getattr(results.tasks_output[0], "raw", "No details available.")
                    st.write(planner_output)

                with tab2:
                    st.markdown("### Analyst's Analysis")
                    analyst_output = getattr(results.tasks_output[1], "raw", "No details available.")
                    st.write(analyst_output)

                    if enable_advanced_analysis:
                        create_visualizations(analyst_output)

            st.success(f"Analysis completed in {elapsed_time:.2f} seconds.")
            token_usage = getattr(results, "token_usage", None)
            if token_usage:
                st.markdown("#### Token Usage")
                st.json(token_usage)

            if writer_output:
                report_path = generate_pdf_report(writer_output)
                with open(report_path, "rb") as report_file:
                    st.download_button("Download Report", data=report_file, file_name="Patent_Report.pdf")

        except Exception as e:
            st.error(f"An error occurred during execution: {e}")

st.sidebar.markdown("---")
st.sidebar.markdown("### Reference:")