DrishtiSharma commited on
Commit
b19df44
·
verified ·
1 Parent(s): 06099ab

Update app.py

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