Spaces:
Build error
Build error
Update app.py
Browse files4 unmodified lines5678910111213141516171819202122232425262710 unmodified lines38394041424344454647484950515253545556575859606162636414 unmodified lines79808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412517 unmodified lines1431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232244 unmodified linesfrom google.oauth2 import service_accountfrom googleapiclient.discovery import buildfrom streamlit_chat import message as st_messageimport plotly.express as pxfrom langchain.schema import HumanMessage, SystemMessage, AIMessagefrom langchain.chat_models import ChatOpenAIfrom langchain.memory import ConversationBufferWindowMemoryfrom langchain.prompts import PromptTemplateimport warningsimport timefrom langchain_groq import ChatGroqimport numpy as npfrom dotenv import load_dotenvimport rewarnings.filterwarnings("ignore", category=DeprecationWarning)# Load environment variablesload_dotenv()GROQ_API_KEY=os.getenv("GROQ_API_KEY")llm = ChatGroq(model="llama-3.1-70b-versatile")PROMPT_TEMPLATE = """10 unmodified lines3. Provide information in a single sentence or a short, structured response.4. If the requested information isn’t available or verifiable, respond with "Information not available."#### Example Output Format:"Company: {entity} | Requested Information: {extracted_information}"Begin extraction."""def get_llm_response(entity, query):# Ensure entity and query are not Noneentity = entity or "Unknown Entity"query = query or "Information not provided"# Format the prompt with the entity and queryformatted_prompt = PROMPT_TEMPLATE.format(entity=entity, query=query)# Pass the formatted prompt as a SystemMessage and get the responseresponse = llm([SystemMessage(content=formatted_prompt)])return response[0].content# Set up the pagest.set_page_config(page_title="DataScribe", page_icon=":notebook_with_decorative_cover:", layout="wide")# Sidebar navigationwith st.sidebar:selected = option_menu("DataScribe Menu",14 unmodified linesif "column_selection" not in st.session_state:st.session_state["column_selection"] = None# Helper function for Google Sheets API setupdef get_google_sheet_data(sheet_id, range_name):credentials = service_account.Credentials.from_service_account_info(st.secrets["gcp_service_account"])service = build('sheets', 'v4', credentials=credentials)sheet = service.spreadsheets()result = sheet.values().get(spreadsheetId=sheet_id, range=range_name).execute()values = result.get('values', [])return pd.DataFrame(values[1:], columns=values[0])# Function to write results back to Google Sheetsdef update_google_sheet(sheet_id, range_name, data):credentials = service_account.Credentials.from_service_account_info(st.secrets["gcp_service_account"])service = build('sheets', 'v4', credentials=credentials)sheet = service.spreadsheets()body = {'values': [data.columns.tolist()] + data.values.tolist()}sheet.values().update(spreadsheetId=sheet_id,range=range_name,valueInputOption="RAW",body=body).execute()# Home Pageif selected == "Home":st.markdown("""### Welcome to DataScribe**DataScribe** is an AI-powered tool designed to extract structured information from the webbased on entities in your data file. Start by uploading a CSV or Google Sheet and defining acustom search query.""")st.image("https://via.placeholder.com/1200x400.png?text=DataScribe+AI+Agent+Dashboard") # Placeholder banner image# Upload Data Sectionelif selected == "Upload Data":st.header("Upload or Connect Your Data")# CSV Uploaddata_source = st.radio("Choose data source:", ["CSV File", "Google Sheets"])if data_source == "CSV File":17 unmodified lines# Define Query Sectionelif selected == "Define Query":st.header("Define Your Custom Query")#entity = st.text_input("Enter the entity name")#query = st.text_input("Enter the query (e.g., 'contact information for {entity}')")if st.session_state["data"] is not None:column_selection = st.selectbox("Select the primary column for entities", options=st.session_state["data"].columns)query_template = st.text_input("Define your query template", "Get me the email for {company}")st.session_state["query_template"] = query_templatest.session_state["column_selection"] = column_selection # Store column selection in session statest.write("### Example query preview")if column_selection:# Convert sample_entity to string to avoid replace errorssample_entity = str(st.session_state["data"][column_selection].iloc[0])example_query = query_template.replace("{company}", sample_entity)st.code(example_query)else:st.warning("Please upload data first.")# if st.button("Extract Information"):# if entity and query:# response_text = get_llm_response(entity, query)# st.write(response_text)# Extract Information Section with Progress Barelif selected == "Extract Information":st.header("Extract Information")if st.session_state.get("query_template") and st.session_state["data"] is not None and st.session_state["column_selection"] is not None:st.write("Data extraction is in progress. This may take a few moments.")# Progress bar initializationprogress_bar = st.progress(0)column_selection = st.session_state["column_selection"]progress_step = 1.0 / len(st.session_state["data"][column_selection])results = []for i, entity in enumerate(st.session_state["data"][column_selection]):# Prepare the prompt for the modeluser_message = st.session_state["query_template"].replace("{company}", str(entity))formatted_prompt = PROMPT_TEMPLATE.format(entity=entity, query=user_message)# Generate response from the modelresponse = llm([SystemMessage(content=formatted_prompt)])# Collect the model's responseresult_text = response[0].content if response else "Information not available"results.append({"Entity": entity, "Extracted Information": result_text})# Update the progress barprogress_bar.progress((i + 1) * progress_step)# Save and display resultsst.session_state["results"] = pd.DataFrame(results)st.write("### Extracted Information")st.dataframe(st.session_state["results"])# View & Download Section with Google Sheets Updateelif selected == "View & Download":st.header("View and Download Results")if st.session_state["results"] is not None:st.write("### Extracted Data Table")st.dataframe(st.session_state["results"])# Download as CSVcsv_data = st.session_state["results"].to_csv(index=False)st.download_button("Download as CSV", csv_data, "datascribe_results.csv", "text/csv")# Option to update Google Sheetsheet_id = st.text_input("Enter Google Sheet ID to update with results")range_name = st.text_input("Enter range (e.g., Sheet1!A1)")if st.button("Update Google Sheet"):try:update_google_sheet(sheet_id, range_name, st.session_state["results"])st.success("Google Sheet updated successfully!")except Exception as e:st.error(f"Failed to update Google Sheet: {e}")else:st.warning("No data available to view or download.")4 unmodified lines56789101112131415161718192010 unmodified lines31323334353637383940414243444546474814 unmodified lines63646566676869707117 unmodified lines89909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351364 unmodified linesfrom google.oauth2 import service_accountfrom googleapiclient.discovery import buildfrom streamlit_chat import message as st_messagefrom langchain.schema import SystemMessagefrom langchain_groq import ChatGroqfrom dotenv import load_dotenvimport warningswarnings.filterwarnings("ignore", category=DeprecationWarning)# Load environment variablesload_dotenv()GROQ_API_KEY = os.getenv("GROQ_API_KEY")llm = ChatGroq(model="llama-3.1-70b-versatile")PROMPT_TEMPLATE = """10 unmodified lines3. Provide information in a single sentence or a short, structured response.4. If the requested information isn’t available or verifiable, respond with "Information not available."Begin extraction."""def get_llm_response(entity, query):formatted_prompt = PROMPT_TEMPLATE.format(entity=entity, query=query)response = llm([SystemMessage(content=formatted_prompt)])return response[0].content if response else "Information not available"# Streamlit Setupst.set_page_config(page_title="DataScribe", page_icon=":notebook_with_decorative_cover:", layout="wide")# Sidebar Navigationwith st.sidebar:selected = option_menu("DataScribe Menu",14 unmodified linesif "column_selection" not in st.session_state:st.session_state["column_selection"] = None# Upload Data Sectionif selected == "Upload Data":st.header("Upload or Connect Your Data")data_source = st.radio("Choose data source:", ["CSV File", "Google Sheets"])if data_source == "CSV File":17 unmodified lines# Define Query Sectionelif selected == "Define Query":st.header("Define Your Custom Query")if st.session_state["data"] is not None:column_selection = st.selectbox("Select the primary column for entities", options=st.session_state["data"].columns)query_template = st.text_input("Define your query template", "Get me the email for {company}")st.session_state["query_template"] = query_templatest.session_state["column_selection"] = column_selectionst.write("### Example query preview")if column_selection:sample_entity = str(st.session_state["data"][column_selection].iloc[0])example_query = query_template.replace("{company}", sample_entity)st.code(example_query)else:st.warning("Please upload data first.")# Extract Information Section with Progress Barelif selected == "Extract Information":st.header("Extract Information")if st.session_state.get("query_template") and st.session_state["data"] is not None and st.session_state["column_selection"] is not None:st.write("Data extraction is in progress. This may take a few moments.")progress_bar = st.progress(0)column_selection = st.session_state["column_selection"]progress_step = 1.0 / len(st.session_state["data"][column_selection])results = []for i, entity in enumerate(st.session_state["data"][column_selection]):user_message = st.session_state["query_template"].replace("{company}", str(entity))result_text = get_llm_response(entity, user_message)results.append({"Entity": entity, "Extracted Information": result_text})progress_bar.progress((i + 1) * progress_step)st.session_state["results"] = pd.DataFrame(results)st.write("### Extracted Information")st.dataframe(st.session_state["results"])# View & Download Sectionelif selected == "View & Download":st.header("View and Download Results")if st.session_state["results"] is not None:st.write("### Extracted Data Table")st.dataframe(st.session_state["results"])csv_data = st.session_state["results"].to_csv(index=False)st.download_button("Download as CSV", csv_data, "datascribe_results.csv", "text/csv")else:st.warning("No data available to view or download.")
app.py+11-99