Spaces:
Sleeping
Sleeping
samiee2213
commited on
Update app.py
Browse files
app.py
CHANGED
@@ -2,159 +2,54 @@ import streamlit as st
|
|
2 |
from streamlit_option_menu import option_menu
|
3 |
import pandas as pd
|
4 |
import os
|
5 |
-
from google.oauth2 import service_account
|
6 |
-
from googleapiclient.discovery import build
|
7 |
-
from streamlit_chat import message as st_message
|
8 |
-
import plotly.express as px
|
9 |
-
import re
|
10 |
-
import streamlit as st
|
11 |
-
import gspread
|
12 |
-
from google.oauth2.service_account import Credentials
|
13 |
import warnings
|
14 |
-
import time
|
15 |
-
from langchain.schema import HumanMessage, SystemMessage, AIMessage
|
16 |
-
from langchain.chat_models import ChatOpenAI
|
17 |
-
from langchain.memory import ConversationBufferWindowMemory
|
18 |
-
from langchain.prompts import PromptTemplate
|
19 |
from langchain_community.utilities import GoogleSerperAPIWrapper
|
20 |
from langchain.agents import initialize_agent, Tool
|
21 |
from langchain.agents import AgentType
|
22 |
from langchain_groq import ChatGroq
|
23 |
-
import numpy as np
|
24 |
-
import gspread
|
25 |
from dotenv import load_dotenv
|
26 |
-
|
|
|
|
|
27 |
|
28 |
warnings.filterwarnings("ignore", category=DeprecationWarning)
|
29 |
|
30 |
-
#google sheet
|
31 |
-
scopes = ["https://www.googleapis.com/auth/spreadsheets"]
|
32 |
-
creds = Credentials.from_service_account_file("credentials.json", scopes=scopes)
|
33 |
-
client = gspread.authorize(creds)
|
34 |
-
|
35 |
|
36 |
#environment
|
37 |
load_dotenv()
|
38 |
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
|
39 |
SERPER_API_KEY = os.getenv("SERPER_API_KEY")
|
40 |
-
|
41 |
-
|
42 |
-
#session state variables
|
43 |
-
if "results" not in st.session_state:
|
44 |
-
st.session_state["results"] = []
|
45 |
-
|
46 |
-
|
47 |
-
# Initialize Google Serper API wrapper
|
48 |
search = GoogleSerperAPIWrapper(serp_api_key=SERPER_API_KEY)
|
49 |
-
|
50 |
|
51 |
-
# Create the system and human messages for dynamic query processing
|
52 |
-
system_message_content = """
|
53 |
-
You are a helpful assistant designed to answer questions by extracting information from the web and external sources. Your goal is to provide the most relevant, concise, and accurate response to user queries.
|
54 |
-
"""
|
55 |
|
56 |
-
# Define the tool list
|
57 |
tools = [
|
58 |
Tool(
|
59 |
name="Web Search",
|
60 |
func=search.run,
|
61 |
-
description=
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
62 |
)
|
63 |
]
|
64 |
|
65 |
-
|
66 |
-
agent = initialize_agent(
|
67 |
-
tools,
|
68 |
-
ChatGroq(api_key=GROQ_API_KEY, model="llama-3.1-70b-versatile"),
|
69 |
-
agent_type=AgentType.SELF_ASK_WITH_SEARCH,
|
70 |
-
verbose=True,
|
71 |
-
memory=ConversationBufferWindowMemory(k=5, return_messages=True)
|
72 |
-
)
|
73 |
-
|
74 |
-
# Function to perform the web search and get results
|
75 |
-
def perform_web_search(query, max_retries=3, delay=2):
|
76 |
-
retries = 0
|
77 |
-
while retries < max_retries:
|
78 |
-
try:
|
79 |
-
search_results = search.run(query)
|
80 |
-
return search_results
|
81 |
-
except Exception as e:
|
82 |
-
retries += 1
|
83 |
-
st.warning(f"Web search failed for query '{query}'. Retrying ({retries}/{max_retries})...")
|
84 |
-
time.sleep(delay)
|
85 |
-
st.error(f"Failed to perform web search for query '{query}' after {max_retries} retries.")
|
86 |
-
return "NaN"
|
87 |
-
|
88 |
-
def update_google_sheet(sheet_id, range_name, data):
|
89 |
-
try:
|
90 |
-
# Define the Google Sheets API scope
|
91 |
-
scopes = ["https://www.googleapis.com/auth/spreadsheets"]
|
92 |
-
creds = Credentials.from_service_account_file("credentials.json", scopes=scopes)
|
93 |
-
client = gspread.authorize(creds)
|
94 |
-
|
95 |
-
# Open the Google Sheet and specify the worksheet
|
96 |
-
sheet = client.open_by_key(sheet_id).worksheet(range_name.split("!")[0])
|
97 |
-
|
98 |
-
# Prepare data for update
|
99 |
-
data_to_update = [data.columns.tolist()] + data.values.tolist()
|
100 |
-
|
101 |
-
# Clear the existing content in the specified range and update it with new data
|
102 |
-
sheet.clear()
|
103 |
-
sheet.update(range_name, data_to_update)
|
104 |
-
|
105 |
-
st.success("Data successfully updated in the Google Sheet!")
|
106 |
-
except Exception as e:
|
107 |
-
st.error(f"Error updating Google Sheet: {e}")
|
108 |
-
# Function to get LLM response for dynamic queries
|
109 |
-
|
110 |
-
def get_llm_response(entity, query, web_results):
|
111 |
-
prompt = f"""
|
112 |
-
Extract relevant {query} (e.g., email, phone number) from the following web results for the entity: {entity}.
|
113 |
-
Web Results: {web_results}
|
114 |
-
"""
|
115 |
-
|
116 |
-
human_message_content = f"""
|
117 |
-
Entity: {entity}
|
118 |
-
Query: {query}
|
119 |
-
Web Results: {web_results}
|
120 |
-
"""
|
121 |
-
|
122 |
-
try:
|
123 |
-
response = agent.invoke([system_message_content, human_message_content], handle_parsing_errors=True)
|
124 |
-
extracted_info = response.get("output", "Information not available").strip()
|
125 |
|
126 |
-
# Clean up irrelevant parts of the response
|
127 |
-
cleaned_info = re.sub(r"(Thought:|Action:)[^A-Za-z0-9]*", "", extracted_info).strip()
|
128 |
-
return cleaned_info
|
129 |
-
except Exception as e:
|
130 |
-
return "NaN"
|
131 |
-
|
132 |
-
# Retry logic for multiple web searches if necessary
|
133 |
-
def refine_answer_with_searches(entity, query, max_retries=3):
|
134 |
-
search_results = perform_web_search(query.format(entity=entity))
|
135 |
-
extracted_answer = get_llm_response(entity, query, search_results)
|
136 |
-
|
137 |
-
if len(extracted_answer.split()) <= 2 or "not available" in extracted_answer.lower():
|
138 |
-
search_results = perform_web_search(query.format(entity=entity))
|
139 |
-
extracted_answer = get_llm_response(entity, query, search_results)
|
140 |
-
|
141 |
-
return extracted_answer, search_results
|
142 |
-
|
143 |
-
# Setup Google Sheets data fetch
|
144 |
-
def get_google_sheet_data(sheet_id, range_name):
|
145 |
-
# Define the Google Sheets API scope
|
146 |
-
scopes = ["https://www.googleapis.com/auth/spreadsheets"]
|
147 |
-
creds = Credentials.from_service_account_file("credentials.json", scopes=scopes)
|
148 |
-
client = gspread.authorize(creds)
|
149 |
-
service = build("sheets", "v4", credentials=creds)
|
150 |
-
sheet = service.spreadsheets()
|
151 |
-
result = sheet.values().get(spreadsheetId=sheet_id, range=range_name).execute()
|
152 |
-
values = result.get("values", [])
|
153 |
-
return pd.DataFrame(values[1:], columns=values[0])
|
154 |
-
|
155 |
-
#streamlitconfiguration
|
156 |
st.set_page_config(page_title="DataScribe", page_icon=":notebook_with_decorative_cover:", layout="wide")
|
157 |
-
|
|
|
|
|
158 |
with st.sidebar:
|
159 |
selected = option_menu(
|
160 |
"DataScribe Menu",
|
@@ -163,437 +58,19 @@ with st.sidebar:
|
|
163 |
menu_icon="cast",
|
164 |
default_index=0
|
165 |
)
|
166 |
-
|
167 |
if selected == "Home":
|
168 |
-
|
169 |
-
<h1 style="text-align:center; color:#4CAF50; font-size: 40px;">🚀 Welcome to DataScribe</h1>
|
170 |
-
<p style="text-align:center; font-size: 18px; color:#333;">An AI-powered information extraction tool to streamline data retrieval and analysis.</p>
|
171 |
-
""", unsafe_allow_html=True)
|
172 |
-
|
173 |
-
st.markdown("""---""")
|
174 |
-
|
175 |
-
def feature_card(title, description, icon, page):
|
176 |
-
col1, col2 = st.columns([1, 4])
|
177 |
-
with col1:
|
178 |
-
st.markdown(f"<div style='font-size: 40px; text-align:center;'>{icon}</div>", unsafe_allow_html=True)
|
179 |
-
with col2:
|
180 |
-
if st.button(f"{title}", key=title, help=description):
|
181 |
-
st.session_state.selected_page = page
|
182 |
-
st.markdown(f"<p style='font-size: 14px; color:#555;'>{description}</p>", unsafe_allow_html=True)
|
183 |
-
|
184 |
-
col1, col2 = st.columns([1, 1])
|
185 |
-
|
186 |
-
with col1:
|
187 |
-
feature_card(
|
188 |
-
title="Upload Data",
|
189 |
-
description="Upload data from CSV or Google Sheets to get started with your extraction.",
|
190 |
-
icon="📄",
|
191 |
-
page="Upload Data"
|
192 |
-
)
|
193 |
-
|
194 |
-
with col2:
|
195 |
-
feature_card(
|
196 |
-
title="Define Custom Queries",
|
197 |
-
description="Set custom search queries for each entity in your dataset for specific information retrieval.",
|
198 |
-
icon="🔍",
|
199 |
-
page="Define Query"
|
200 |
-
)
|
201 |
-
|
202 |
-
col1, col2 = st.columns([1, 1])
|
203 |
-
|
204 |
-
with col1:
|
205 |
-
feature_card(
|
206 |
-
title="Run Automated Searches",
|
207 |
-
description="Execute automated web searches and extract relevant information using an AI-powered agent.",
|
208 |
-
icon="🤖",
|
209 |
-
page="Extract Information"
|
210 |
-
)
|
211 |
-
|
212 |
-
with col2:
|
213 |
-
feature_card(
|
214 |
-
title="View & Download Results",
|
215 |
-
description="View extracted data in a structured format and download as a CSV or update Google Sheets.",
|
216 |
-
icon="📊",
|
217 |
-
page="View & Download"
|
218 |
-
)
|
219 |
|
220 |
elif selected == "Upload Data":
|
221 |
-
|
222 |
-
|
223 |
-
|
224 |
-
if data_source == "CSV Files":
|
225 |
-
if "data" in st.session_state:
|
226 |
-
st.success("Data uploaded successfully! Here is a preview:")
|
227 |
-
st.dataframe(st.session_state["data"].head(10)) # Display only the first 10 rows for a cleaner view
|
228 |
-
else:
|
229 |
-
uploaded_files = st.file_uploader("Upload your CSV files", type=["csv"], accept_multiple_files=True)
|
230 |
-
|
231 |
-
if uploaded_files is not None:
|
232 |
-
dfs = []
|
233 |
-
for uploaded_file in uploaded_files:
|
234 |
-
try:
|
235 |
-
df = pd.read_csv(uploaded_file)
|
236 |
-
dfs.append(df)
|
237 |
-
except Exception as e:
|
238 |
-
st.error(f"Error reading file {uploaded_file.name}: {e}")
|
239 |
-
|
240 |
-
if dfs:
|
241 |
-
full_data = pd.concat(dfs, ignore_index=True)
|
242 |
-
st.session_state["data"] = full_data
|
243 |
-
st.success("Data uploaded successfully! Here is a preview:")
|
244 |
-
st.dataframe(full_data.head(10)) # Show preview of first 10 rows
|
245 |
-
else:
|
246 |
-
st.warning("No valid data found in the uploaded files.")
|
247 |
-
|
248 |
-
if st.button("Clear Data"):
|
249 |
-
del st.session_state["data"]
|
250 |
-
st.success("Data has been cleared!")
|
251 |
-
|
252 |
-
elif data_source == "Google Sheets":
|
253 |
-
sheet_id = st.text_input("Enter Google Sheet ID")
|
254 |
-
range_name = st.text_input("Enter the data range (e.g., Sheet1!A1:C100)")
|
255 |
-
|
256 |
-
if sheet_id and range_name:
|
257 |
-
if st.button("Fetch Data"):
|
258 |
-
with st.spinner("Fetching data from Google Sheets..."):
|
259 |
-
try:
|
260 |
-
data = get_google_sheet_data(sheet_id, range_name)
|
261 |
-
st.session_state["data"] = data
|
262 |
-
st.success("Data fetched successfully! Here is a preview:")
|
263 |
-
st.dataframe(data.head(10)) # Show preview of first 10 rows
|
264 |
-
except Exception as e:
|
265 |
-
st.error(f"Error fetching data: {e}")
|
266 |
-
else:
|
267 |
-
st.warning("Please enter both Sheet ID and Range name before fetching data.")
|
268 |
-
|
269 |
-
|
270 |
elif selected == "Define Query":
|
271 |
-
|
272 |
-
|
273 |
-
if "data" not in st.session_state or st.session_state["data"] is None:
|
274 |
-
st.warning("Please upload data first! Use the 'Upload Data' section to upload your data.")
|
275 |
-
else:
|
276 |
-
column = st.selectbox(
|
277 |
-
"Select entity column",
|
278 |
-
st.session_state["data"].columns,
|
279 |
-
help="Select the column that contains the entities for which you want to define queries."
|
280 |
-
)
|
281 |
-
|
282 |
-
st.markdown("""
|
283 |
-
<style>
|
284 |
-
div[data-baseweb="select"] div[data-id="select"] {{
|
285 |
-
background-color: #f0f8ff;
|
286 |
-
}}
|
287 |
-
</style>
|
288 |
-
""", unsafe_allow_html=True)
|
289 |
-
|
290 |
-
st.subheader("Define Fields to Extract")
|
291 |
-
num_fields = st.number_input(
|
292 |
-
"Number of fields to extract",
|
293 |
-
min_value=1,
|
294 |
-
value=1,
|
295 |
-
step=1,
|
296 |
-
help="Specify how many fields you want to extract from each entity."
|
297 |
-
)
|
298 |
-
|
299 |
-
fields = []
|
300 |
-
for i in range(num_fields):
|
301 |
-
field = st.text_input(
|
302 |
-
f"Field {i+1} name",
|
303 |
-
key=f"field_{i}",
|
304 |
-
placeholder=f"Enter field name for {i+1}",
|
305 |
-
help="Name the field you want to extract from the entity."
|
306 |
-
)
|
307 |
-
if field:
|
308 |
-
fields.append(field)
|
309 |
-
|
310 |
-
if fields:
|
311 |
-
st.subheader("Query Template")
|
312 |
-
query_template = st.text_area(
|
313 |
-
"Enter query template (Use '{entity}' to represent each entity)",
|
314 |
-
value=f"Find the {', '.join(fields)} for {{entity}}",
|
315 |
-
help="You can use {entity} as a placeholder to represent each entity in the query."
|
316 |
-
)
|
317 |
-
|
318 |
-
if "{entity}" in query_template:
|
319 |
-
example_entity = str(st.session_state["data"][column].iloc[0])
|
320 |
-
example_query = query_template.replace("{entity}", example_entity)
|
321 |
-
st.write("### Example Query Preview")
|
322 |
-
st.code(example_query)
|
323 |
-
|
324 |
-
if st.button("Save Query Configuration"):
|
325 |
-
if not fields:
|
326 |
-
st.error("Please define at least one field to extract.")
|
327 |
-
elif not query_template:
|
328 |
-
st.error("Please enter a query template.")
|
329 |
-
else:
|
330 |
-
st.session_state["column_selection"] = column
|
331 |
-
st.session_state["query_template"] = query_template
|
332 |
-
st.session_state["extraction_fields"] = fields
|
333 |
-
st.success("Query configuration saved successfully!")
|
334 |
-
|
335 |
-
elif selected == "Extract Information":
|
336 |
-
st.header("Extract Information")
|
337 |
-
|
338 |
-
if "query_template" in st.session_state and "data" in st.session_state:
|
339 |
-
st.write("### Using Query Template:")
|
340 |
-
st.code(st.session_state["query_template"])
|
341 |
-
|
342 |
-
column_selection = st.session_state["column_selection"]
|
343 |
-
entities_column = st.session_state["data"][column_selection]
|
344 |
-
|
345 |
-
col1, col2 = st.columns([2, 1])
|
346 |
-
with col1:
|
347 |
-
st.write("### Selected Entity Column:")
|
348 |
-
st.dataframe(entities_column, use_container_width=True)
|
349 |
-
|
350 |
-
with col2:
|
351 |
-
start_button = st.button("Start Extraction", type="primary", use_container_width=True)
|
352 |
-
|
353 |
-
results_container = st.empty()
|
354 |
-
|
355 |
-
if start_button:
|
356 |
-
with st.spinner("Extracting information..."):
|
357 |
-
progress_bar = st.progress(0)
|
358 |
-
progress_text = st.empty()
|
359 |
-
|
360 |
-
try:
|
361 |
-
results = []
|
362 |
-
for i, selected_entity in enumerate(entities_column):
|
363 |
-
user_query = st.session_state["query_template"].replace("{entity}", str(selected_entity))
|
364 |
-
final_answer, search_results = refine_answer_with_searches(selected_entity, user_query)
|
365 |
-
results.append({
|
366 |
-
"Entity": selected_entity,
|
367 |
-
"Extracted Information": final_answer,
|
368 |
-
"Search Results": search_results
|
369 |
-
})
|
370 |
-
|
371 |
-
progress = (i + 1) / len(entities_column)
|
372 |
-
progress_bar.progress(progress)
|
373 |
-
progress_text.text(f"Processing {i+1}/{len(entities_column)} entities...")
|
374 |
-
|
375 |
-
st.session_state["results"] = results
|
376 |
-
|
377 |
-
progress_bar.empty()
|
378 |
-
progress_text.empty()
|
379 |
-
st.success("Extraction completed successfully!")
|
380 |
-
|
381 |
-
except Exception as e:
|
382 |
-
st.error(f"An error occurred during extraction: {str(e)}")
|
383 |
-
st.session_state.pop("results", None)
|
384 |
-
|
385 |
-
if "results" in st.session_state and st.session_state["results"]:
|
386 |
-
with results_container:
|
387 |
-
results = st.session_state["results"]
|
388 |
-
|
389 |
-
search_query = st.text_input("🔍 Search results", "")
|
390 |
-
|
391 |
-
tab1, tab2 = st.tabs(["Compact View", "Detailed View"])
|
392 |
-
|
393 |
-
with tab1:
|
394 |
-
found_results = False
|
395 |
-
for result in results:
|
396 |
-
if search_query.lower() in str(result["Entity"]).lower() or \
|
397 |
-
search_query.lower() in str(result["Extracted Information"]).lower():
|
398 |
-
found_results = True
|
399 |
-
with st.expander(f"📋 {result['Entity']}", expanded=False):
|
400 |
-
st.markdown("#### Extracted Information")
|
401 |
-
st.write(result["Extracted Information"])
|
402 |
-
|
403 |
-
if not found_results and search_query:
|
404 |
-
st.info("No results found for your search.")
|
405 |
-
|
406 |
-
with tab2:
|
407 |
-
found_results = False
|
408 |
-
for i, result in enumerate(results):
|
409 |
-
if search_query.lower() in str(result["Entity"]).lower() or \
|
410 |
-
search_query.lower() in str(result["Extracted Information"]).lower():
|
411 |
-
found_results = True
|
412 |
-
st.markdown(f"### Entity {i+1}: {result['Entity']}")
|
413 |
-
|
414 |
-
col1, col2 = st.columns(2)
|
415 |
-
|
416 |
-
with col1:
|
417 |
-
st.markdown("#### 📝 Extracted Information")
|
418 |
-
st.info(result["Extracted Information"])
|
419 |
-
|
420 |
-
with col2:
|
421 |
-
st.markdown("#### 🔍 Search Results")
|
422 |
-
st.warning(result["Search Results"])
|
423 |
-
|
424 |
-
st.divider()
|
425 |
-
|
426 |
-
if not found_results and search_query:
|
427 |
-
st.info("No results found for your search.")
|
428 |
-
else:
|
429 |
-
st.warning("Please upload your data and define the query template.")
|
430 |
-
|
431 |
elif selected == "Extract Information":
|
432 |
-
|
433 |
-
|
434 |
-
|
435 |
-
st.write("### Using Query Template:")
|
436 |
-
st.code(st.session_state["query_template"])
|
437 |
-
|
438 |
-
column_selection = st.session_state["column_selection"]
|
439 |
-
entities_column = st.session_state["data"][column_selection]
|
440 |
-
|
441 |
-
col1, col2 = st.columns([2, 1])
|
442 |
-
with col1:
|
443 |
-
st.write("### Selected Entity Column:")
|
444 |
-
st.dataframe(entities_column, use_container_width=True)
|
445 |
-
|
446 |
-
with col2:
|
447 |
-
start_button = st.button("Start Extraction", type="primary", use_container_width=True)
|
448 |
-
|
449 |
-
results_container = st.empty()
|
450 |
-
|
451 |
-
if start_button:
|
452 |
-
with st.spinner("Extracting information..."):
|
453 |
-
progress_bar = st.progress(0)
|
454 |
-
progress_text = st.empty()
|
455 |
-
|
456 |
-
try:
|
457 |
-
results = []
|
458 |
-
for i, selected_entity in enumerate(entities_column):
|
459 |
-
user_query = st.session_state["query_template"].replace("{entity}", str(selected_entity))
|
460 |
-
final_answer, search_results = refine_answer_with_searches(selected_entity, user_query)
|
461 |
-
results.append({
|
462 |
-
"Entity": selected_entity,
|
463 |
-
"Extracted Information": final_answer,
|
464 |
-
"Search Results": search_results
|
465 |
-
})
|
466 |
-
|
467 |
-
progress = (i + 1) / len(entities_column)
|
468 |
-
progress_bar.progress(progress)
|
469 |
-
progress_text.text(f"Processing {i+1}/{len(entities_column)} entities...")
|
470 |
-
|
471 |
-
st.session_state["results"] = results
|
472 |
-
|
473 |
-
progress_bar.empty()
|
474 |
-
progress_text.empty()
|
475 |
-
st.success("Extraction completed successfully!")
|
476 |
-
|
477 |
-
except Exception as e:
|
478 |
-
st.error(f"An error occurred during extraction: {str(e)}")
|
479 |
-
st.session_state.pop("results", None)
|
480 |
-
|
481 |
-
if "results" in st.session_state and st.session_state["results"]:
|
482 |
-
with results_container:
|
483 |
-
results = st.session_state["results"]
|
484 |
-
|
485 |
-
search_query = st.text_input("🔍 Search results", "")
|
486 |
-
|
487 |
-
tab1, tab2 = st.tabs(["Compact View", "Detailed View"])
|
488 |
-
|
489 |
-
with tab1:
|
490 |
-
found_results = False
|
491 |
-
for result in results:
|
492 |
-
if search_query.lower() in str(result["Entity"]).lower() or \
|
493 |
-
search_query.lower() in str(result["Extracted Information"]).lower():
|
494 |
-
found_results = True
|
495 |
-
with st.expander(f"📋 {result['Entity']}", expanded=False):
|
496 |
-
st.markdown("#### Extracted Information")
|
497 |
-
st.write(result["Extracted Information"])
|
498 |
-
|
499 |
-
if not found_results and search_query:
|
500 |
-
st.info("No results found for your search.")
|
501 |
-
|
502 |
-
with tab2:
|
503 |
-
found_results = False
|
504 |
-
for i, result in enumerate(results):
|
505 |
-
if search_query.lower() in str(result["Entity"]).lower() or \
|
506 |
-
search_query.lower() in str(result["Extracted Information"]).lower():
|
507 |
-
found_results = True
|
508 |
-
st.markdown(f"### Entity {i+1}: {result['Entity']}")
|
509 |
-
|
510 |
-
col1, col2 = st.columns(2)
|
511 |
-
|
512 |
-
with col1:
|
513 |
-
st.markdown("#### 📝 Extracted Information")
|
514 |
-
st.info(result["Extracted Information"])
|
515 |
-
|
516 |
-
with col2:
|
517 |
-
st.markdown("#### 🔍 Search Results")
|
518 |
-
st.warning(result["Search Results"])
|
519 |
-
|
520 |
-
st.divider()
|
521 |
-
|
522 |
-
if not found_results and search_query:
|
523 |
-
st.info("No results found for your search.")
|
524 |
-
else:
|
525 |
-
st.warning("Please upload your data and define the query template.")
|
526 |
-
|
527 |
elif selected == "View & Download":
|
528 |
-
|
529 |
-
|
530 |
-
if "results" in st.session_state and st.session_state["results"]:
|
531 |
-
results_df = pd.DataFrame(st.session_state["results"])
|
532 |
-
st.write("### Results Preview")
|
533 |
-
|
534 |
-
# Display the results preview
|
535 |
-
if "Extracted Information" in results_df.columns and "Search Results" in results_df.columns:
|
536 |
-
st.dataframe(results_df.style.map(lambda val: 'background-color: #d3f4ff' if isinstance(val, str) else '', subset=["Extracted Information", "Search Results"]))
|
537 |
-
else:
|
538 |
-
st.warning("Required columns are missing in results data.")
|
539 |
-
|
540 |
-
# Download options
|
541 |
-
download_option = st.selectbox(
|
542 |
-
"Select data to download:",
|
543 |
-
["All Results", "Extracted Information", "Web Results"]
|
544 |
-
)
|
545 |
-
|
546 |
-
if download_option == "All Results":
|
547 |
-
data_to_download = results_df
|
548 |
-
elif download_option == "Extracted Information":
|
549 |
-
data_to_download = results_df[["Entity", "Extracted Information"]]
|
550 |
-
elif download_option == "Web Results":
|
551 |
-
data_to_download = results_df[["Entity", "Search Results"]]
|
552 |
-
|
553 |
-
st.download_button(
|
554 |
-
label=f"Download {download_option} as CSV",
|
555 |
-
data=data_to_download.to_csv(index=False),
|
556 |
-
file_name=f"{download_option.lower().replace(' ', '_')}.csv",
|
557 |
-
mime="text/csv"
|
558 |
-
)
|
559 |
-
|
560 |
-
# Option to update Google Sheets
|
561 |
-
update_option = st.selectbox(
|
562 |
-
"Do you want to update Google Sheets?",
|
563 |
-
["No", "Yes"]
|
564 |
-
)
|
565 |
-
|
566 |
-
if update_option == "Yes":
|
567 |
-
if 'sheet_id' not in st.session_state:
|
568 |
-
st.session_state.sheet_id = ''
|
569 |
-
if 'range_name' not in st.session_state:
|
570 |
-
st.session_state.range_name = ''
|
571 |
-
|
572 |
-
# Input fields for Google Sheets ID and Range
|
573 |
-
sheet_id = st.text_input("Enter Google Sheet ID", value=st.session_state.sheet_id)
|
574 |
-
range_name = st.text_input("Enter Range (e.g., 'Sheet1!A1')", value=st.session_state.range_name)
|
575 |
-
|
576 |
-
if sheet_id and range_name:
|
577 |
-
st.session_state.sheet_id = sheet_id
|
578 |
-
st.session_state.range_name = range_name
|
579 |
-
|
580 |
-
# Prepare data for update
|
581 |
-
data_to_update = [results_df.columns.tolist()] + results_df.values.tolist()
|
582 |
|
583 |
-
# Update Google Sheets button
|
584 |
-
if st.button("Update Google Sheet"):
|
585 |
-
try:
|
586 |
-
if '!' not in range_name:
|
587 |
-
st.error("Invalid range format. Please use the format 'SheetName!Range'.")
|
588 |
-
else:
|
589 |
-
sheet_name, cell_range = range_name.split('!', 1)
|
590 |
-
sheet = client.open_by_key(sheet_id).worksheet(sheet_name)
|
591 |
-
sheet.clear()
|
592 |
-
sheet.update(f"{cell_range}", data_to_update)
|
593 |
-
st.success("Data updated in the Google Sheet!")
|
594 |
-
except Exception as e:
|
595 |
-
st.error(f"Error updating Google Sheet: {e}")
|
596 |
-
else:
|
597 |
-
st.warning("Please enter both the Sheet ID and Range name before updating.")
|
598 |
-
else:
|
599 |
-
st.warning("No results available to view. Please run the extraction process.")
|
|
|
2 |
from streamlit_option_menu import option_menu
|
3 |
import pandas as pd
|
4 |
import os
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
5 |
import warnings
|
|
|
|
|
|
|
|
|
|
|
6 |
from langchain_community.utilities import GoogleSerperAPIWrapper
|
7 |
from langchain.agents import initialize_agent, Tool
|
8 |
from langchain.agents import AgentType
|
9 |
from langchain_groq import ChatGroq
|
|
|
|
|
10 |
from dotenv import load_dotenv
|
11 |
+
from funcs.llm import LLM
|
12 |
+
from views import home,upload_data,define_query,extract_information,view_and_download
|
13 |
+
from views.extract_information import ExtractInformation
|
14 |
|
15 |
warnings.filterwarnings("ignore", category=DeprecationWarning)
|
16 |
|
|
|
|
|
|
|
|
|
|
|
17 |
|
18 |
#environment
|
19 |
load_dotenv()
|
20 |
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
|
21 |
SERPER_API_KEY = os.getenv("SERPER_API_KEY")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
22 |
search = GoogleSerperAPIWrapper(serp_api_key=SERPER_API_KEY)
|
23 |
+
model = ChatGroq(model="llama-3.2-11b-vision-preview")
|
24 |
|
|
|
|
|
|
|
|
|
25 |
|
|
|
26 |
tools = [
|
27 |
Tool(
|
28 |
name="Web Search",
|
29 |
func=search.run,
|
30 |
+
description=(
|
31 |
+
"This is your primary tool to search the web when you need information "
|
32 |
+
"that is not available in the given context. Always provide a precise and specific search query "
|
33 |
+
"when using this tool. Use it to retrieve up-to-date or detailed information such as locations, dates, "
|
34 |
+
"contacts, addresses, company details, or any specific entity-related facts. "
|
35 |
+
"Avoid making assumptions—only use the Web Search if the context does not have the needed details."
|
36 |
+
"\n\nImportant Instructions:\n"
|
37 |
+
"- Do not generate answers based on assumptions.\n"
|
38 |
+
"- Use Web Search for facts that require external verification.\n"
|
39 |
+
"- Provide concise and accurate search queries.\n"
|
40 |
+
"- Return the most authoritative and recent data."
|
41 |
+
),
|
42 |
+
return_direct=False,
|
43 |
+
handle_tool_error=True
|
44 |
)
|
45 |
]
|
46 |
|
47 |
+
llm = LLM(tools,model,search)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
48 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
49 |
st.set_page_config(page_title="DataScribe", page_icon=":notebook_with_decorative_cover:", layout="wide")
|
50 |
+
if "results" not in st.session_state:
|
51 |
+
st.session_state["results"] = []
|
52 |
+
|
53 |
with st.sidebar:
|
54 |
selected = option_menu(
|
55 |
"DataScribe Menu",
|
|
|
58 |
menu_icon="cast",
|
59 |
default_index=0
|
60 |
)
|
|
|
61 |
if selected == "Home":
|
62 |
+
home.CreatePage()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
63 |
|
64 |
elif selected == "Upload Data":
|
65 |
+
upload_data.CreatePage()
|
66 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
67 |
elif selected == "Define Query":
|
68 |
+
define_query.CreatePage()
|
69 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
70 |
elif selected == "Extract Information":
|
71 |
+
extract = ExtractInformation(llm)
|
72 |
+
extract.CreatePage()
|
73 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
74 |
elif selected == "View & Download":
|
75 |
+
view_and_download.CreatePage()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
76 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|