Spaces:
Build error
Build error
Update app.py
Browse files6 unmodified lines7891011125 unmodified lines1819202122232425262728 unmodified lines565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910021 unmodified lines12212312412512612712812913013113213313413513613713813914014114214314414537 unmodified lines18318418518618718818910 unmodified lines2002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432441 unmodified line2462472482492502512523 unmodified lines2562572582592602612622632642652667 unmodified lines2742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233241 unmodified line3263273283293303313323333343353363373383393403413423433443453463473483493503513526 unmodified linesfrom streamlit_chat import message as st_messageimport plotly.express as pximport reimport warningsimport timefrom langchain.schema import HumanMessage, SystemMessage, AIMessage5 unmodified linesfrom langchain.agents import AgentTypefrom langchain_groq import ChatGroqimport numpy as npfrom dotenv import load_dotenvwarnings.filterwarnings("ignore", category=DeprecationWarning)#environmentload_dotenv()GROQ_API_KEY = os.getenv("GROQ_API_KEY")28 unmodified lines)# Function to perform the web search and get resultsdef perform_web_search(query):search_results = search.run(query)return search_results# Function to get LLM response for dynamic queriesdef get_llm_response(entity, query, web_results):prompt = f"""Extract relevant {query} (e.g., email, phone number) from the following web results for the entity: {entity}.Web Results: {web_results}"""human_message_content = f"""Entity: {entity}Query: {query}Web Results: {web_results}"""response = agent.invoke([system_message_content, human_message_content])extracted_info = response.get("output", "Information not available").strip()# Clean up irrelevant parts of the responsecleaned_info = re.sub(r"(Thought:|Action:)[^A-Za-z0-9]*", "", extracted_info).strip()return cleaned_info# Retry logic for multiple web searches if necessarydef refine_answer_with_searches(entity, query, max_retries=3):search_results = perform_web_search(query.format(entity=entity))extracted_answer = get_llm_response(entity, query, search_results)retries = 0while retries < max_retries:if len(extracted_answer.split()) <= 2 or "not available" in extracted_answer.lower():retries += 1time.sleep(2)search_results = perform_web_search(query.format(entity=entity))extracted_answer = get_llm_response(entity, query, search_results)else:breakreturn extracted_answer, search_results# Setup Google Sheets data fetch21 unmodified lines)if selected == "Home":st.markdown("""<h1 style="text-align:center; color:#4CAF50; font-size: 40px;">🚀 Welcome to DataScribe</h1><p style="text-align:center; font-size: 18px;">An AI-powered information extraction tool to streamline data retrieval and analysis.</p>""", unsafe_allow_html=True)st.markdown("""---""")def feature_card(title, description, icon, page):col1, col2 = st.columns([1, 4])with col1:st.markdown(f"<div style='font-size: 40px;'>{icon}</div>", unsafe_allow_html=True)with col2:if st.button(f"{title}", key=title):st.session_state.selected_page = pagest.write(description)col1, col2 = st.columns([1, 1])with col1:37 unmodified linesif data_source == "CSV Files":if "data" in st.session_state:st.success("Data uploaded successfully! Here is a preview:")st.dataframe(st.session_state["data"])else:uploaded_files = st.file_uploader("Upload your CSV files", type=["csv"], accept_multiple_files=True)10 unmodified linesfull_data = pd.concat(dfs, ignore_index=True)st.session_state["data"] = full_datast.success("Data uploaded successfully! Here is a preview:")st.dataframe(full_data)else:st.warning("No valid data found in the uploaded files.")elif data_source == "Google Sheets":sheet_id = st.text_input("Enter Google Sheet ID")range_name = st.text_input("Enter the data range (e.g., Sheet1!A1:C100)")if st.button("Fetch Data"):try:data = get_google_sheet_data(sheet_id, range_name)st.session_state["data"] = datast.write("Data fetched successfully. Here is a preview:")st.dataframe(data)except Exception as e:st.error(f"Error fetching data: {e}")elif selected == "Define Query":st.header("Define Your Custom Query")if "data" not in st.session_state or st.session_state["data"] is None:st.warning("Please upload data first!")else:column = st.selectbox("Select entity column", st.session_state["data"].columns)st.markdown(f"""<style>div[data-baseweb="select"] div[data-id="select"] {{background-color: #f0f8ff;}}</style>""", unsafe_allow_html=True)st.subheader("Define Fields to Extract")num_fields = st.number_input("Number of fields to extract", min_value=1, value=1, step=1)fields = []for i in range(num_fields):field = st.text_input(f"Field {i+1} name", key=f"field_{i}")if field:fields.append(field)1 unmodified linest.subheader("Query Template")query_template = st.text_area("Enter query template (Use '{entity}' to represent each entity)",value=f"Find the {', '.join(fields)} for {{entity}}")if "{entity}" in query_template:3 unmodified linesst.code(example_query)if st.button("Save Query Configuration"):st.session_state["column_selection"] = columnst.session_state["query_template"] = query_templatest.session_state["extraction_fields"] = fieldsst.success("Query configuration saved!")elif selected == "Extract Information":st.header("Extract Information")7 unmodified linesst.write("### Selected Entity Column:")st.dataframe(entities_column)st.write("Data extraction is in progress. This may take a few moments.")# Custom styled progress barprogress_bar = st.progress(0)# Custom CSS for a cute progress bar stylest.markdown("""<style>.stProgress > div {background-color: #FFB6C1; /* Light pink */border-radius: 20px;height: 15px;}</style>""", unsafe_allow_html=True)try:results = []for i, selected_entity in enumerate(entities_column):user_query = st.session_state["query_template"].replace("{entity}", str(selected_entity))final_answer, search_results = refine_answer_with_searches(selected_entity, user_query)results.append({"Entity": selected_entity,"Extracted Information": final_answer,"Search Results": search_results})# Update progress bar with a smooth and cute animationprogress_bar.progress(int((i + 1) / len(entities_column) * 100))st.session_state["results"] = resultsst.write("### Extracted Information")for result in results:st.write(f"**Entity:** {result['Entity']}")st.write(f"**Extracted Information:** {result['Extracted Information']}")st.write("### Web Results:")for result in results:st.write(result["Search Results"])except Exception as e:st.error(f"An error occurred while extracting information: {e}")else:st.warning("Please upload your data and define the query template.")elif selected == "View & Download":st.header("View & Download Results")1 unmodified lineresults_df = pd.DataFrame(st.session_state["results"])st.write("### Results Preview")st.dataframe(results_df.style.applymap(lambda val: 'background-color: #d3f4ff' if isinstance(val, str) else '', subset=["Extracted Information", "Search Results"]))st.download_button(label="Download all results as CSV",data=results_df.to_csv(index=False),file_name="extracted_results.csv",mime="text/csv")st.download_button(label="Download Extracted Information as CSV",data=results_df[["Entity", "Extracted Information"]].to_csv(index=False),file_name="extracted_information.csv",mime="text/csv")st.download_button(label="Download Web Results as CSV",data=results_df[["Entity", "Search Results"]].to_csv(index=False),file_name="web_results.csv",mime="text/csv")else:st.warning("No results available to view. Please run the extraction process.")6 unmodified lines7891011121314155 unmodified lines2122232425262728293031323328 unmodified lines626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013121 unmodified lines15315415515615715815916016116216316416516616716816917017117217317437 unmodified lines21221321421521621721810 unmodified lines2292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962971 unmodified line2993003013023033043053063 unmodified lines3103113123133143153163173183193203213223233247 unmodified lines3323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713721 unmodified line3743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304316 unmodified linesfrom streamlit_chat import message as st_messageimport plotly.express as pximport reimport streamlit as stimport gspreadfrom google.oauth2.service_account import Credentialsimport warningsimport timefrom langchain.schema import HumanMessage, SystemMessage, AIMessage5 unmodified linesfrom langchain.agents import AgentTypefrom langchain_groq import ChatGroqimport numpy as npimport gspreadfrom dotenv import load_dotenvwarnings.filterwarnings("ignore", category=DeprecationWarning)scopes = ["https://www.googleapis.com/auth/spreadsheets"]creds = Credentials.from_service_account_file("credentials.json", scopes=scopes)client = gspread.authorize(creds)#environmentload_dotenv()GROQ_API_KEY = os.getenv("GROQ_API_KEY")28 unmodified lines)# Function to perform the web search and get resultsdef perform_web_search(query, max_retries=3, delay=2):retries = 0while retries < max_retries:try:search_results = search.run(query)return search_resultsexcept Exception as e:retries += 1st.warning(f"Web search failed for query '{query}'. Retrying ({retries}/{max_retries})...")time.sleep(delay)st.error(f"Failed to perform web search for query '{query}' after {max_retries} retries.")return "NaN"def update_google_sheet(sheet_id, range_name, data):try:# Define the Google Sheets API scopescopes = ["https://www.googleapis.com/auth/spreadsheets"]creds = Credentials.from_service_account_file("credentials.json", scopes=scopes)client = gspread.authorize(creds)# Open the Google Sheet and specify the worksheetsheet = client.open_by_key(sheet_id).worksheet(range_name.split("!")[0])# Prepare data for updatedata_to_update = [data.columns.tolist()] + data.values.tolist()# Clear the existing content in the specified range and update it with new datasheet.clear()sheet.update(range_name, data_to_update)st.success("Data successfully updated in the Google Sheet!")except Exception as e:st.error(f"Error updating Google Sheet: {e}")# Function to get LLM response for dynamic queriesdef get_llm_response(entity, query, web_results):prompt = f"""Extract relevant {query} (e.g., email, phone number) from the following web results for the entity: {entity}.Web Results: {web_results}"""human_message_content = f"""Entity: {entity}Query: {query}Web Results: {web_results}"""try:response = agent.invoke([system_message_content, human_message_content], handle_parsing_errors=True)extracted_info = response.get("output", "Information not available").strip()# Clean up irrelevant parts of the responsecleaned_info = re.sub(r"(Thought:|Action:)[^A-Za-z0-9]*", "", extracted_info).strip()return cleaned_infoexcept Exception as e:return "NaN"# Retry logic for multiple web searches if necessarydef refine_answer_with_searches(entity, query, max_retries=3):search_results = perform_web_search(query.format(entity=entity))extracted_answer = get_llm_response(entity, query, search_results)if len(extracted_answer.split()) <= 2 or "not available" in extracted_answer.lower():search_results = perform_web_search(query.format(entity=entity))extracted_answer = get_llm_response(entity, query, search_results)return extracted_answer, search_results# Setup Google Sheets data fetch21 unmodified lines)if selected == "Home":st.markdown("""<h1 style="text-align:center; color:#4CAF50; font-size: 40px;">🚀 Welcome to DataScribe</h1><p style="text-align:center; font-size: 18px; color:#333;">An AI-powered information extraction tool to streamline data retrieval and analysis.</p>""", unsafe_allow_html=True)st.markdown("""---""")def feature_card(title, description, icon, page):col1, col2 = st.columns([1, 4])with col1:st.markdown(f"<div style='font-size: 40px; text-align:center;'>{icon}</div>", unsafe_allow_html=True)with col2:if st.button(f"{title}", key=title, help=description):st.session_state.selected_page = pagest.markdown(f"<p style='font-size: 14px; color:#555;'>{description}</p>", unsafe_allow_html=True)col1, col2 = st.columns([1, 1])with col1:37 unmodified linesif data_source == "CSV Files":if "data" in st.session_state:st.success("Data uploaded successfully! Here is a preview:")st.dataframe(st.session_state["data"].head(10)) # Display only the first 10 rows for a cleaner viewelse:uploaded_files = st.file_uploader("Upload your CSV files", type=["csv"], accept_multiple_files=True)10 unmodified linesfull_data = pd.concat(dfs, ignore_index=True)st.session_state["data"] = full_datast.success("Data uploaded successfully! Here is a preview:")st.dataframe(full_data.head(10)) # Show preview of first 10 rowselse:st.warning("No valid data found in the uploaded files.")if st.button("Clear Data"):del st.session_state["data"]st.success("Data has been cleared!")elif data_source == "Google Sheets":sheet_id = st.text_input("Enter Google Sheet ID")range_name = st.text_input("Enter the data range (e.g., Sheet1!A1:C100)")if sheet_id and range_name:if st.button("Fetch Data"):with st.spinner("Fetching data from Google Sheets..."):try:data = get_google_sheet_data(sheet_id, range_name)st.session_state["data"] = datast.success("Data fetched successfully! Here is a preview:")st.dataframe(data.head(10)) # Show preview of first 10 rowsexcept Exception as e:st.error(f"Error fetching data: {e}")else:st.warning("Please enter both Sheet ID and Range name before fetching data.")elif selected == "Define Query":st.header("Define Your Custom Query")if "data" not in st.session_state or st.session_state["data"] is None:st.warning("Please upload data first! Use the 'Upload Data' section to upload your data.")else:column = st.selectbox("Select entity column",st.session_state["data"].columns,help="Select the column that contains the entities for which you want to define queries.")st.markdown("""<style>div[data-baseweb="select"] div[data-id="select"] {{background-color: #f0f8ff;}}</style>""", unsafe_allow_html=True)st.subheader("Define Fields to Extract")num_fields = st.number_input("Number of fields to extract",min_value=1,value=1,step=1,help="Specify how many fields you want to extract from each entity.")fields = []for i in range(num_fields):field = st.text_input(f"Field {i+1} name",key=f"field_{i}",placeholder=f"Enter field name for {i+1}",help="Name the field you want to extract from the entity.")if field:fields.append(field)1 unmodified linest.subheader("Query Template")query_template = st.text_area("Enter query template (Use '{entity}' to represent each entity)",value=f"Find the {', '.join(fields)} for {{entity}}",help="You can use {entity} as a placeholder to represent each entity in the query.")if "{entity}" in query_template:3 unmodified linesst.code(example_query)if st.button("Save Query Configuration"):if not fields:st.error("Please define at least one field to extract.")elif not query_template:st.error("Please enter a query template.")else:st.session_state["column_selection"] = columnst.session_state["query_template"] = query_templatest.session_state["extraction_fields"] = fieldsst.success("Query configuration saved successfully!")elif selected == "Extract Information":st.header("Extract Information")7 unmodified linesst.write("### Selected Entity Column:")st.dataframe(entities_column)if st.button("Start Extraction"):st.write("Data extraction is in progress. This may take a few moments.")# Custom styled progress barprogress_bar = st.progress(0)try:results = []for i, selected_entity in enumerate(entities_column):user_query = st.session_state["query_template"].replace("{entity}", str(selected_entity))final_answer, search_results = refine_answer_with_searches(selected_entity, user_query)results.append({"Entity": selected_entity,"Extracted Information": final_answer,"Search Results": search_results})# Update progress bar with a smooth and cute animationprogress_bar.progress(int((i + 1) / len(entities_column) * 100))st.session_state["results"] = resultsst.write("### Extracted Information")for result in results:st.write(f"**Entity:** {result['Entity']}")st.write(f"**Extracted Information:** {result['Extracted Information']}")st.write("### Web Results:")for result in results:st.write(result["Search Results"])except Exception as e:st.error(f"An error occurred while extracting information: {e}")else:st.warning("Please upload your data and define the query template.")elif selected == "View & Download":st.header("View & Download Results")1 unmodified lineresults_df = pd.DataFrame(st.session_state["results"])st.write("### Results Preview")# Display results with some background color for the relevant columnsst.dataframe(results_df.style.applymap(lambda val: 'background-color: #d3f4ff' if isinstance(val, str) else '', subset=["Extracted Information", "Search Results"]))download_option = st.selectbox("Select data to download:",["All Results", "Extracted Information", "Web Results"])if download_option == "All Results":data_to_download = results_dfelif download_option == "Extracted Information":data_to_download = results_df[["Entity", "Extracted Information"]]elif download_option == "Web Results":data_to_download = results_df[["Entity", "Search Results"]]st.download_button(label=f"Download {download_option} as CSV",data=data_to_download.to_csv(index=False),file_name=f"{download_option.lower().replace(' ', '_')}.csv",mime="text/csv")# To ensure the inputs and button are persistent, store their values in session_stateif 'sheet_id' not in st.session_state:st.session_state.sheet_id = ''if 'range_name' not in st.session_state:st.session_state.range_name = ''sheet_id = st.text_input("Enter Google Sheet ID", value=st.session_state.sheet_id)range_name = st.text_input("Enter Range (e.g., 'Sheet1!A1')", value=st.session_state.range_name)if sheet_id and range_name:st.session_state.sheet_id = sheet_idst.session_state.range_name = range_name# Define data_to_update to update the Google Sheetdata_to_update = [results_df.columns.tolist()] + results_df.values.tolist()# Update Google Sheets buttonif st.button("Update Google Sheet"):try:if '!' not in range_name:st.error("Invalid range format. Please use the format 'SheetName!Range'.")else:sheet_name, cell_range = range_name.split('!', 1)sheet = client.open_by_key(sheet_id).worksheet(sheet_name)sheet.clear() # Clear the existing data before updatingsheet.update(f"{cell_range}", data_to_update) # Update the data to the specified rangest.success("Data updated in the Google Sheet!")except Exception as e:st.error(f"Error updating Google Sheet: {e}")else:st.warning("Please enter both the Sheet ID and Range name before updating.")else:st.warning("No results available to view. Please run the extraction process.")
app.py+188-109