Spaces:
Sleeping
Sleeping
| 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 matplotlib.pyplot as plt | |
| import tempfile | |
| import time | |
| # Title and Sidebar | |
| 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." | |
| ) | |
| # User Inputs | |
| patent_area = st.text_input('Enter Patent Technology Area', value="Artificial Intelligence") | |
| stakeholder = st.text_input('Enter Stakeholder', value="Patent Attorneys") | |
| # Advanced Options | |
| st.sidebar.subheader("Advanced Options") | |
| enable_advanced_analysis = st.sidebar.checkbox("Enable Advanced Analysis", value=True) | |
| enable_custom_visualization = st.sidebar.checkbox("Enable Custom Visualizations", value=True) | |
| # Optional Customization | |
| st.sidebar.subheader("Agent Customization") | |
| with st.sidebar.expander("Customize Agent Goals", expanded=False): | |
| enable_customization = st.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 Object | |
| #================= | |
| llm = ChatGroq(groq_api_key=os.getenv("GROQ_API_KEY"), model="groq/llama-3.3-70b-versatile") | |
| #================= | |
| # Crew Agents | |
| #================= | |
| 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 | |
| ) | |
| #================= | |
| # Crew Tasks | |
| #================= | |
| 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. Provide structured output with fields 'Category' and 'Values' for visualization.\n" | |
| "3. Collaborate with the Planner and Writer to align on data needs." | |
| ), | |
| 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, charts=None, table_data=None): | |
| """Generate a professional PDF report from the Crew output.""" | |
| with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as temp_pdf: | |
| pdf = FPDF() | |
| pdf.add_page() | |
| pdf.set_font("Arial", size=12) | |
| pdf.set_auto_page_break(auto=True, margin=15) | |
| # Title | |
| pdf.set_font("Arial", size=16, style="B") | |
| pdf.cell(200, 10, txt="Patent Insights Report", ln=True, align="C") | |
| pdf.ln(10) | |
| # Content | |
| pdf.set_font("Arial", size=12) | |
| pdf.multi_cell(0, 10, txt=result) | |
| # Add charts if provided | |
| if charts: | |
| for chart_path in charts: | |
| pdf.add_page() | |
| pdf.image(chart_path, x=10, y=20, w=180) | |
| # Add tables if provided | |
| if table_data: | |
| pdf.add_page() | |
| pdf.set_font("Arial", size=10) | |
| for row in table_data: | |
| pdf.cell(200, 10, txt=str(row), ln=True) | |
| # Save PDF | |
| pdf.output(temp_pdf.name) | |
| return temp_pdf.name | |
| def create_visualizations(analyst_output): | |
| """Create visualizations for advanced insights.""" | |
| chart_paths = [] | |
| if enable_custom_visualization and analyst_output: | |
| try: | |
| st.markdown("#### Debugging Analyst Output") | |
| st.write(analyst_output) | |
| # Validate and format analyst output | |
| if isinstance(analyst_output, list) and all(isinstance(item, dict) for item in analyst_output): | |
| data = pd.DataFrame(analyst_output) | |
| if 'Category' in data.columns and 'Values' in data.columns: | |
| st.markdown("### Advanced Visualization") | |
| # Create a bar chart | |
| fig = px.bar(data, x="Category", y="Values", title="Patent Trends by Category") | |
| st.plotly_chart(fig) | |
| # Save chart to a file for embedding in PDF | |
| with tempfile.NamedTemporaryFile(delete=False, suffix=".png") as temp_chart: | |
| fig.write_image(temp_chart.name) | |
| chart_paths.append(temp_chart.name) | |
| else: | |
| st.warning("Data does not have the required columns 'Category' and 'Values'.") | |
| else: | |
| st.warning("Analyst output is not in the correct format for visualization.") | |
| except Exception as e: | |
| st.error(f"Failed to create visualizations: {e}") | |
| return chart_paths | |
| def display_table(analyst_output): | |
| """Display tabular data for detailed insights.""" | |
| table_data = [] | |
| if analyst_output and isinstance(analyst_output, list): | |
| try: | |
| st.markdown("#### Debugging Analyst Output for Table") | |
| st.write(analyst_output) | |
| data = pd.DataFrame(analyst_output) | |
| st.markdown("### Data Table") | |
| st.dataframe(data) | |
| table_data = data.to_dict(orient="records") | |
| except Exception as e: | |
| st.error(f"Failed to display table: {e}") | |
| return table_data | |
| if st.button("Generate Patent Insights"): | |
| with st.spinner('Processing...'): | |
| try: | |
| start_time = time.time() | |
| results = crew.kickoff(inputs={"topic": patent_area, "stakeholder": stakeholder}) | |
| elapsed_time = time.time() - start_time | |
| # Display Final Report (Writer's Output) | |
| 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.") | |
| # Option for Detailed Insights | |
| with st.expander("Explore Detailed Insights"): | |
| tab1, tab2 = st.tabs(["Planner's Insights", "Analyst's Analysis"]) | |
| # Planner's Output | |
| with tab1: | |
| st.markdown("### Planner's Insights") | |
| planner_output = getattr(results.tasks_output[0], "raw", "No details available.") | |
| st.write(planner_output) | |
| # Analyst's Output | |
| with tab2: | |
| st.markdown("### Analyst's Analysis") | |
| analyst_output = getattr(results.tasks_output[1], "raw", "No details available.") | |
| st.write(analyst_output) | |
| # Generate visualizations if enabled | |
| charts = [] | |
| if enable_advanced_analysis: | |
| charts = create_visualizations(analyst_output) | |
| # Display tabular data | |
| table_data = display_table(analyst_output) | |
| # Display Token Usage and Execution Time | |
| 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) | |
| # Generate PDF Report | |
| if writer_output: | |
| pdf_path = generate_pdf_report(writer_output, charts=charts, table_data=table_data) | |
| with open(pdf_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}") |