Spaces:
Running
Running
DrishtiSharma
commited on
Create interim_v1.py
Browse files- mylab/interim_v1.py +166 -0
mylab/interim_v1.py
ADDED
@@ -0,0 +1,166 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import pandas as pd
|
3 |
+
import sqlite3
|
4 |
+
import os
|
5 |
+
import json
|
6 |
+
from pathlib import Path
|
7 |
+
from datetime import datetime, timezone
|
8 |
+
from crewai import Agent, Crew, Process, Task
|
9 |
+
from crewai.tools import tool
|
10 |
+
from langchain_groq import ChatGroq
|
11 |
+
from langchain_openai import ChatOpenAI
|
12 |
+
from langchain.schema.output import LLMResult
|
13 |
+
from langchain_core.callbacks.base import BaseCallbackHandler
|
14 |
+
from langchain_community.tools.sql_database.tool import (
|
15 |
+
InfoSQLDatabaseTool,
|
16 |
+
ListSQLDatabaseTool,
|
17 |
+
QuerySQLCheckerTool,
|
18 |
+
QuerySQLDataBaseTool,
|
19 |
+
)
|
20 |
+
from langchain_community.utilities.sql_database import SQLDatabase
|
21 |
+
from datasets import load_dataset
|
22 |
+
import tempfile
|
23 |
+
|
24 |
+
# API Key
|
25 |
+
os.environ["GROQ_API_KEY"] = st.secrets.get("GROQ_API_KEY", "")
|
26 |
+
|
27 |
+
st.title("Blah Blah App Using CrewAI π")
|
28 |
+
st.write("Analyze datasets using natural language queries powered by SQL and CrewAI.")
|
29 |
+
|
30 |
+
# Initialize LLM
|
31 |
+
llm = None
|
32 |
+
|
33 |
+
# Model Selection
|
34 |
+
model_choice = st.radio("Select LLM", ["GPT-4o", "llama-3.3-70b"], index=0, horizontal=True)
|
35 |
+
|
36 |
+
|
37 |
+
# API Key Validation and LLM Initialization
|
38 |
+
groq_api_key = os.getenv("GROQ_API_KEY")
|
39 |
+
openai_api_key = os.getenv("OPENAI_API_KEY")
|
40 |
+
|
41 |
+
if model_choice == "llama-3.3-70b":
|
42 |
+
if not groq_api_key:
|
43 |
+
st.error("Groq API key is missing. Please set the GROQ_API_KEY environment variable.")
|
44 |
+
llm = None
|
45 |
+
else:
|
46 |
+
llm = ChatGroq(groq_api_key=groq_api_key, model="groq/llama-3.3-70b-versatile")
|
47 |
+
elif model_choice == "GPT-4o":
|
48 |
+
if not openai_api_key:
|
49 |
+
st.error("OpenAI API key is missing. Please set the OPENAI_API_KEY environment variable.")
|
50 |
+
llm = None
|
51 |
+
else:
|
52 |
+
llm = ChatOpenAI(api_key=openai_api_key, model="gpt-4o")
|
53 |
+
|
54 |
+
# Initialize session state for data persistence
|
55 |
+
if "df" not in st.session_state:
|
56 |
+
st.session_state.df = None
|
57 |
+
|
58 |
+
# Dataset Input
|
59 |
+
input_option = st.radio("Select Dataset Input:", ["Use Hugging Face Dataset", "Upload CSV File"])
|
60 |
+
if input_option == "Use Hugging Face Dataset":
|
61 |
+
dataset_name = st.text_input("Enter Hugging Face Dataset Name:", value="HUPD/hupd")
|
62 |
+
if st.button("Load Dataset"):
|
63 |
+
try:
|
64 |
+
with st.spinner("Loading dataset..."):
|
65 |
+
dataset = load_dataset(dataset_name, name="sample", split="train", trust_remote_code=True, uniform_split=True)
|
66 |
+
st.session_state.df = pd.DataFrame(dataset)
|
67 |
+
st.success(f"Dataset '{dataset_name}' loaded successfully!")
|
68 |
+
st.dataframe(st.session_state.df.head())
|
69 |
+
except Exception as e:
|
70 |
+
st.error(f"Error: {e}")
|
71 |
+
elif input_option == "Upload CSV File":
|
72 |
+
uploaded_file = st.file_uploader("Upload CSV File:", type=["csv"])
|
73 |
+
if uploaded_file:
|
74 |
+
st.session_state.df = pd.read_csv(uploaded_file)
|
75 |
+
st.success("File uploaded successfully!")
|
76 |
+
st.dataframe(st.session_state.df.head())
|
77 |
+
|
78 |
+
|
79 |
+
if st.session_state.df is not None:
|
80 |
+
# Database setup
|
81 |
+
temp_dir = tempfile.TemporaryDirectory()
|
82 |
+
db_path = os.path.join(temp_dir.name, "patent_data.db")
|
83 |
+
connection = sqlite3.connect(db_path)
|
84 |
+
st.session_state.df.to_sql("patents", connection, if_exists="replace", index=False)
|
85 |
+
db = SQLDatabase.from_uri(f"sqlite:///{db_path}")
|
86 |
+
|
87 |
+
# SQL Tools
|
88 |
+
@tool("list_tables")
|
89 |
+
def list_tables() -> str:
|
90 |
+
"""List all tables in the patent database."""
|
91 |
+
return ListSQLDatabaseTool(db=db).invoke("")
|
92 |
+
|
93 |
+
@tool("tables_schema")
|
94 |
+
def tables_schema(tables: str) -> str:
|
95 |
+
"""Get schema and sample rows for given tables."""
|
96 |
+
return InfoSQLDatabaseTool(db=db).invoke(tables)
|
97 |
+
|
98 |
+
@tool("execute_sql")
|
99 |
+
def execute_sql(sql_query: str) -> str:
|
100 |
+
"""Execute a SQL query against the patent database."""
|
101 |
+
return QuerySQLDataBaseTool(db=db).invoke(sql_query)
|
102 |
+
|
103 |
+
# --- CrewAI Agents for Patent Analysis ---
|
104 |
+
patent_sql_dev = Agent(
|
105 |
+
role="Patent Data Analyst",
|
106 |
+
goal="Extract patent data using optimized SQL queries.",
|
107 |
+
backstory="An expert in writing optimized SQL queries for complex patent databases.",
|
108 |
+
llm=llm,
|
109 |
+
tools=[list_tables, tables_schema, execute_sql],
|
110 |
+
)
|
111 |
+
|
112 |
+
patent_data_analyst = Agent(
|
113 |
+
role="Patent Data Analyst",
|
114 |
+
goal="Analyze the data and produce insights.",
|
115 |
+
backstory="A seasoned analyst who identifies trends and patterns in datasets.",
|
116 |
+
llm=llm,
|
117 |
+
)
|
118 |
+
|
119 |
+
patent_report_writer = Agent(
|
120 |
+
role="Patent Report Writer",
|
121 |
+
goal="Summarize patent insights into a clear report.",
|
122 |
+
backstory="Expert in summarizing patent data insights into comprehensive reports.",
|
123 |
+
llm=llm,
|
124 |
+
)
|
125 |
+
|
126 |
+
# --- Crew Tasks ---
|
127 |
+
extract_data = Task(
|
128 |
+
description="Extract patents related to the query: {query}.",
|
129 |
+
expected_output="Patent data matching the query.",
|
130 |
+
agent=patent_sql_dev,
|
131 |
+
)
|
132 |
+
|
133 |
+
analyze_data = Task(
|
134 |
+
description="Analyze the extracted patent data for query: {query}.",
|
135 |
+
expected_output="Analysis text summarizing findings.",
|
136 |
+
agent=patent_data_analyst,
|
137 |
+
context=[extract_data],
|
138 |
+
)
|
139 |
+
|
140 |
+
write_report = Task(
|
141 |
+
description="Summarize analysis into an executive report.",
|
142 |
+
expected_output="Markdown report of insights.",
|
143 |
+
agent=patent_report_writer,
|
144 |
+
context=[analyze_data],
|
145 |
+
)
|
146 |
+
|
147 |
+
# Assemble Crew
|
148 |
+
crew = Crew(
|
149 |
+
agents=[patent_sql_dev, patent_data_analyst, patent_report_writer],
|
150 |
+
tasks=[extract_data, analyze_data, write_report],
|
151 |
+
process=Process.sequential,
|
152 |
+
verbose=True,
|
153 |
+
)
|
154 |
+
|
155 |
+
#Query Input for Patent Analysis
|
156 |
+
query = st.text_area("Enter Patent Analysis Query:", placeholder="e.g., 'How many patents related to Machine Learning were filed after 2016?'")
|
157 |
+
if st.button("Submit Query"):
|
158 |
+
with st.spinner("Processing your query..."):
|
159 |
+
inputs = {"query": query}
|
160 |
+
result = crew.kickoff(inputs=inputs)
|
161 |
+
st.markdown("### π Patent Analysis Report")
|
162 |
+
st.markdown(result)
|
163 |
+
|
164 |
+
temp_dir.cleanup()
|
165 |
+
else:
|
166 |
+
st.info("Please load a patent dataset to proceed.")
|