Spaces:
Sleeping
Sleeping
Update test.py
Browse files
test.py
CHANGED
|
@@ -2,22 +2,53 @@ 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 tempfile
|
| 9 |
import time
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
# Title and Application Introduction
|
| 12 |
-
st.title("Patent
|
| 13 |
st.sidebar.write(
|
| 14 |
-
"This
|
| 15 |
)
|
| 16 |
|
| 17 |
# User Input Section
|
| 18 |
st.sidebar.header("User Inputs")
|
| 19 |
-
patent_area = st.text_input(
|
| 20 |
-
stakeholder = st.text_input(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
# Advanced Options
|
| 23 |
st.sidebar.header("Advanced Options")
|
|
@@ -46,8 +77,6 @@ with st.sidebar.expander("Customize Agent Goals", expanded=False):
|
|
| 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 Initialization
|
| 50 |
-
llm = ChatGroq(groq_api_key=os.getenv("GROQ_API_KEY"), model="groq/llama-3.3-70b-versatile")
|
| 51 |
|
| 52 |
# Agent Definitions
|
| 53 |
planner = Agent(
|
|
@@ -89,9 +118,10 @@ plan = Task(
|
|
| 89 |
"1. Research recent trends in {topic} patent filings and innovation.\n"
|
| 90 |
"2. Identify key players and emerging technologies.\n"
|
| 91 |
"3. Provide recommendations for stakeholders on strategic directions.\n"
|
| 92 |
-
"4.
|
|
|
|
| 93 |
),
|
| 94 |
-
expected_output="A research document with structured insights and
|
| 95 |
agent=planner
|
| 96 |
)
|
| 97 |
|
|
@@ -99,20 +129,23 @@ write = Task(
|
|
| 99 |
description=(
|
| 100 |
"1. Use the Planner's and Analyst's outputs to craft a professional patent insights document.\n"
|
| 101 |
"2. Include key findings, visual aids, and actionable strategies.\n"
|
| 102 |
-
"3.
|
| 103 |
-
"4.
|
|
|
|
| 104 |
),
|
| 105 |
-
expected_output="A polished, stakeholder-ready patent insights document.",
|
| 106 |
agent=writer
|
| 107 |
)
|
| 108 |
|
| 109 |
analyse = Task(
|
| 110 |
description=(
|
| 111 |
"1. Perform statistical analysis of patent filing trends, innovation hot spots, and growth projections.\n"
|
| 112 |
-
"2.
|
| 113 |
-
"3.
|
|
|
|
|
|
|
| 114 |
),
|
| 115 |
-
expected_output="A detailed statistical analysis with actionable insights
|
| 116 |
agent=analyst
|
| 117 |
)
|
| 118 |
|
|
@@ -123,7 +156,6 @@ crew = Crew(
|
|
| 123 |
)
|
| 124 |
|
| 125 |
# PDF Report Generation
|
| 126 |
-
|
| 127 |
def generate_pdf_report(result, charts=None, table_data=None, metadata=None):
|
| 128 |
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as temp_pdf:
|
| 129 |
pdf = FPDF()
|
|
@@ -132,7 +164,7 @@ def generate_pdf_report(result, charts=None, table_data=None, metadata=None):
|
|
| 132 |
pdf.set_auto_page_break(auto=True, margin=15)
|
| 133 |
|
| 134 |
pdf.set_font("Arial", size=16, style="B")
|
| 135 |
-
pdf.cell(200, 10, txt="Patent
|
| 136 |
pdf.ln(10)
|
| 137 |
|
| 138 |
if metadata:
|
|
@@ -145,12 +177,17 @@ def generate_pdf_report(result, charts=None, table_data=None, metadata=None):
|
|
| 145 |
|
| 146 |
if charts:
|
| 147 |
for chart_path in charts:
|
| 148 |
-
|
| 149 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 150 |
|
| 151 |
if table_data:
|
| 152 |
pdf.add_page()
|
| 153 |
pdf.set_font("Arial", size=10)
|
|
|
|
| 154 |
for row in table_data:
|
| 155 |
pdf.cell(200, 10, txt=str(row), ln=True)
|
| 156 |
|
|
@@ -158,7 +195,6 @@ def generate_pdf_report(result, charts=None, table_data=None, metadata=None):
|
|
| 158 |
return temp_pdf.name
|
| 159 |
|
| 160 |
# Data Validation
|
| 161 |
-
|
| 162 |
def validate_analyst_output(analyst_output):
|
| 163 |
if not analyst_output:
|
| 164 |
st.warning("No data available for analysis.")
|
|
@@ -173,19 +209,41 @@ def validate_analyst_output(analyst_output):
|
|
| 173 |
return analyst_output
|
| 174 |
|
| 175 |
# Visualization and Table Display
|
| 176 |
-
|
| 177 |
def create_visualizations(analyst_output):
|
| 178 |
chart_paths = []
|
| 179 |
validated_data = validate_analyst_output(analyst_output)
|
| 180 |
if validated_data:
|
| 181 |
data = pd.DataFrame(validated_data)
|
| 182 |
try:
|
| 183 |
-
|
| 184 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 185 |
with tempfile.NamedTemporaryFile(delete=False, suffix=".png") as temp_chart:
|
| 186 |
-
|
| 187 |
chart_paths.append(temp_chart.name)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 188 |
except Exception as e:
|
|
|
|
| 189 |
st.error(f"Error generating visualization: {e}")
|
| 190 |
return chart_paths
|
| 191 |
|
|
@@ -199,42 +257,50 @@ def display_table(analyst_output):
|
|
| 199 |
return table_data
|
| 200 |
|
| 201 |
# Main Execution Block
|
| 202 |
-
|
| 203 |
-
if
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
charts =
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
from crewai import Agent, Task, Crew
|
| 3 |
import os
|
| 4 |
from langchain_groq import ChatGroq
|
| 5 |
+
from langchain_openai import ChatOpenAI
|
| 6 |
from fpdf import FPDF
|
| 7 |
import pandas as pd
|
| 8 |
import plotly.express as px
|
| 9 |
import tempfile
|
| 10 |
import time
|
| 11 |
+
import logging
|
| 12 |
+
|
| 13 |
+
# Setup logging
|
| 14 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 15 |
|
| 16 |
# Title and Application Introduction
|
| 17 |
+
st.title("Patent Strategy and Innovation Consultant")
|
| 18 |
st.sidebar.write(
|
| 19 |
+
"This application uses AI to provide actionable insights and comprehensive analysis for patent-related strategies."
|
| 20 |
)
|
| 21 |
|
| 22 |
# User Input Section
|
| 23 |
st.sidebar.header("User Inputs")
|
| 24 |
+
patent_area = st.text_input("Enter Patent Technology Area", value="Transparent Antennas for Windshields")
|
| 25 |
+
stakeholder = st.text_input("Enter Stakeholder", value="Patent Attorneys")
|
| 26 |
+
|
| 27 |
+
# Initialize LLM
|
| 28 |
+
llm = None
|
| 29 |
+
|
| 30 |
+
# Model Selection
|
| 31 |
+
#st.header("Model Selection")
|
| 32 |
+
model_choice = st.selectbox("Select LLM", ["OpenAI Model","Groq-based LLM"])
|
| 33 |
+
|
| 34 |
+
# API Key Validation and LLM Initialization
|
| 35 |
+
groq_api_key = os.getenv("GROQ_API_KEY")
|
| 36 |
+
openai_api_key = os.getenv("OPENAI_API_KEY")
|
| 37 |
+
|
| 38 |
+
#llm = ChatGroq(groq_api_key=os.getenv("GROQ_API_KEY"), model="groq/llama-3.3-70b-versatile")
|
| 39 |
+
|
| 40 |
+
if model_choice == "Groq-based LLM":
|
| 41 |
+
if not groq_api_key:
|
| 42 |
+
st.error("Groq API key is missing. Please set the GROQ_API_KEY environment variable.")
|
| 43 |
+
llm = None
|
| 44 |
+
else:
|
| 45 |
+
llm = ChatGroq(groq_api_key=groq_api_key, model="groq/llama-3.3-70b-versatile")
|
| 46 |
+
elif model_choice == "OpenAI Model":
|
| 47 |
+
if not openai_api_key:
|
| 48 |
+
st.error("OpenAI API key is missing. Please set the OPENAI_API_KEY environment variable.")
|
| 49 |
+
llm = None
|
| 50 |
+
else:
|
| 51 |
+
llm = ChatOpenAI(api_key=openai_api_key, model="gpt-4o")
|
| 52 |
|
| 53 |
# Advanced Options
|
| 54 |
st.sidebar.header("Advanced Options")
|
|
|
|
| 77 |
writer_goal = "Craft a professional insights document summarizing trends, strategies, and actionable outcomes for stakeholders."
|
| 78 |
analyst_goal = "Perform detailed statistical analysis of patent filings, growth trends, and innovation distribution."
|
| 79 |
|
|
|
|
|
|
|
| 80 |
|
| 81 |
# Agent Definitions
|
| 82 |
planner = Agent(
|
|
|
|
| 118 |
"1. Research recent trends in {topic} patent filings and innovation.\n"
|
| 119 |
"2. Identify key players and emerging technologies.\n"
|
| 120 |
"3. Provide recommendations for stakeholders on strategic directions.\n"
|
| 121 |
+
"4. Identify key statistics such as top regions, top players, and hot areas of innovation.\n"
|
| 122 |
+
"5. Limit the output to 500 words."
|
| 123 |
),
|
| 124 |
+
expected_output="A research document with structured insights, strategic recommendations, and key statistics.",
|
| 125 |
agent=planner
|
| 126 |
)
|
| 127 |
|
|
|
|
| 129 |
description=(
|
| 130 |
"1. Use the Planner's and Analyst's outputs to craft a professional patent insights document.\n"
|
| 131 |
"2. Include key findings, visual aids, and actionable strategies.\n"
|
| 132 |
+
"3. Suggest strategic directions and highlight untapped innovation areas.\n"
|
| 133 |
+
"4. Incorporate summarized tables for key statistics and example inventions.\n"
|
| 134 |
+
"5. Limit the document to 650 words."
|
| 135 |
),
|
| 136 |
+
expected_output="A polished, stakeholder-ready patent insights document with actionable recommendations.",
|
| 137 |
agent=writer
|
| 138 |
)
|
| 139 |
|
| 140 |
analyse = Task(
|
| 141 |
description=(
|
| 142 |
"1. Perform statistical analysis of patent filing trends, innovation hot spots, and growth projections.\n"
|
| 143 |
+
"2. Identify top regions, key players, and technology combinations.\n"
|
| 144 |
+
"3. Generate visualizations such as heatmaps, bar charts, and multi-line charts for trends.\n"
|
| 145 |
+
"4. Provide structured output with fields 'Category' and 'Values' for visualization.\n"
|
| 146 |
+
"5. Collaborate with the Planner and Writer to align on data needs."
|
| 147 |
),
|
| 148 |
+
expected_output="A detailed statistical analysis with actionable insights, heatmaps, and trends.",
|
| 149 |
agent=analyst
|
| 150 |
)
|
| 151 |
|
|
|
|
| 156 |
)
|
| 157 |
|
| 158 |
# PDF Report Generation
|
|
|
|
| 159 |
def generate_pdf_report(result, charts=None, table_data=None, metadata=None):
|
| 160 |
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as temp_pdf:
|
| 161 |
pdf = FPDF()
|
|
|
|
| 164 |
pdf.set_auto_page_break(auto=True, margin=15)
|
| 165 |
|
| 166 |
pdf.set_font("Arial", size=16, style="B")
|
| 167 |
+
pdf.cell(200, 10, txt="Patent Strategy and Innovation Report", ln=True, align="C")
|
| 168 |
pdf.ln(10)
|
| 169 |
|
| 170 |
if metadata:
|
|
|
|
| 177 |
|
| 178 |
if charts:
|
| 179 |
for chart_path in charts:
|
| 180 |
+
try:
|
| 181 |
+
pdf.add_page()
|
| 182 |
+
pdf.image(chart_path, x=10, y=20, w=180)
|
| 183 |
+
logging.info(f"Successfully included chart: {chart_path}")
|
| 184 |
+
except Exception as e:
|
| 185 |
+
logging.error(f"Failed to include chart in PDF: {chart_path}. Error: {e}")
|
| 186 |
|
| 187 |
if table_data:
|
| 188 |
pdf.add_page()
|
| 189 |
pdf.set_font("Arial", size=10)
|
| 190 |
+
pdf.cell(200, 10, txt="Consolidated Table:", ln=True, align="L")
|
| 191 |
for row in table_data:
|
| 192 |
pdf.cell(200, 10, txt=str(row), ln=True)
|
| 193 |
|
|
|
|
| 195 |
return temp_pdf.name
|
| 196 |
|
| 197 |
# Data Validation
|
|
|
|
| 198 |
def validate_analyst_output(analyst_output):
|
| 199 |
if not analyst_output:
|
| 200 |
st.warning("No data available for analysis.")
|
|
|
|
| 209 |
return analyst_output
|
| 210 |
|
| 211 |
# Visualization and Table Display
|
|
|
|
| 212 |
def create_visualizations(analyst_output):
|
| 213 |
chart_paths = []
|
| 214 |
validated_data = validate_analyst_output(analyst_output)
|
| 215 |
if validated_data:
|
| 216 |
data = pd.DataFrame(validated_data)
|
| 217 |
try:
|
| 218 |
+
if data.empty:
|
| 219 |
+
raise ValueError("Data for visualizations is empty.")
|
| 220 |
+
|
| 221 |
+
bar_chart = px.bar(data, x="Category", y="Values", title="Patent Trends by Category")
|
| 222 |
+
st.plotly_chart(bar_chart)
|
| 223 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".png") as temp_chart:
|
| 224 |
+
bar_chart.write_image(temp_chart.name)
|
| 225 |
+
chart_paths.append(temp_chart.name)
|
| 226 |
+
|
| 227 |
+
pie_chart = px.pie(data, names="Category", values="Values", title="Category Distribution")
|
| 228 |
+
st.plotly_chart(pie_chart)
|
| 229 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".png") as temp_chart:
|
| 230 |
+
pie_chart.write_image(temp_chart.name)
|
| 231 |
+
chart_paths.append(temp_chart.name)
|
| 232 |
+
|
| 233 |
+
heatmap_chart = px.density_heatmap(data, x="Category", y="Values", title="Regional Patent Density")
|
| 234 |
+
st.plotly_chart(heatmap_chart)
|
| 235 |
with tempfile.NamedTemporaryFile(delete=False, suffix=".png") as temp_chart:
|
| 236 |
+
heatmap_chart.write_image(temp_chart.name)
|
| 237 |
chart_paths.append(temp_chart.name)
|
| 238 |
+
|
| 239 |
+
multi_line_chart = px.line(data, x="Category", y="Values", title="Trends Over Time")
|
| 240 |
+
st.plotly_chart(multi_line_chart)
|
| 241 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".png") as temp_chart:
|
| 242 |
+
multi_line_chart.write_image(temp_chart.name)
|
| 243 |
+
chart_paths.append(temp_chart.name)
|
| 244 |
+
|
| 245 |
except Exception as e:
|
| 246 |
+
logging.error(f"Error generating visualization: {e}")
|
| 247 |
st.error(f"Error generating visualization: {e}")
|
| 248 |
return chart_paths
|
| 249 |
|
|
|
|
| 257 |
return table_data
|
| 258 |
|
| 259 |
# Main Execution Block
|
| 260 |
+
if st.button("Generate Insights"):
|
| 261 |
+
if llm is None:
|
| 262 |
+
st.error("Cannot proceed without a valid API key for the selected model.")
|
| 263 |
+
else:
|
| 264 |
+
with st.spinner('Processing...'):
|
| 265 |
+
try:
|
| 266 |
+
start_time = time.time()
|
| 267 |
+
results = crew.kickoff(inputs={"topic": patent_area, "stakeholder": stakeholder})
|
| 268 |
+
elapsed_time = time.time() - start_time
|
| 269 |
+
|
| 270 |
+
writer_output = getattr(results.tasks_output[2], "raw", "No details available.")
|
| 271 |
+
if writer_output:
|
| 272 |
+
st.markdown("### Final Report")
|
| 273 |
+
st.write(writer_output)
|
| 274 |
+
else:
|
| 275 |
+
st.warning("No final report available.")
|
| 276 |
+
|
| 277 |
+
with st.expander("Explore Detailed Insights"):
|
| 278 |
+
tab1, tab2 = st.tabs(["Planner's Insights", "Analyst's Analysis"])
|
| 279 |
+
|
| 280 |
+
with tab1:
|
| 281 |
+
planner_output = getattr(results.tasks_output[0], "raw", "No details available.")
|
| 282 |
+
st.write(planner_output)
|
| 283 |
+
|
| 284 |
+
with tab2:
|
| 285 |
+
analyst_output = getattr(results.tasks_output[1], "raw", "No details available.")
|
| 286 |
+
st.write(analyst_output)
|
| 287 |
+
|
| 288 |
+
charts = []
|
| 289 |
+
if enable_advanced_analysis:
|
| 290 |
+
charts = create_visualizations(analyst_output)
|
| 291 |
+
|
| 292 |
+
table_data = display_table(analyst_output)
|
| 293 |
+
|
| 294 |
+
st.success(f"Analysis completed in {elapsed_time:.2f} seconds.")
|
| 295 |
+
pdf_path = generate_pdf_report(
|
| 296 |
+
writer_output,
|
| 297 |
+
charts=charts,
|
| 298 |
+
table_data=table_data,
|
| 299 |
+
metadata={"Technology Area": patent_area, "Stakeholder": stakeholder}
|
| 300 |
+
)
|
| 301 |
+
with open(pdf_path, "rb") as report_file:
|
| 302 |
+
st.download_button("Download Report", data=report_file, file_name="Patent_Strategy_Report.pdf")
|
| 303 |
+
|
| 304 |
+
except Exception as e:
|
| 305 |
+
logging.error(f"An error occurred during execution: {e}")
|
| 306 |
+
st.error(f"An error occurred during execution: {e}")
|