Sw1ft0 commited on
Commit
5ad7d73
·
1 Parent(s): 0b8b15e

Major approach change. Rewrite app.py, ajust requirements and update .gitignore.

Browse files
Files changed (3) hide show
  1. .gitignore +1 -1
  2. app.py +72 -83
  3. requirements.txt +1 -2
.gitignore CHANGED
@@ -1 +1 @@
1
- testing_files/
 
1
+ data_source/
app.py CHANGED
@@ -1,91 +1,80 @@
1
  import pandas as pd
2
  import gradio as gr
3
- from langchain.agents import initialize_agent, Tool
4
- from langchain_google_genai import ChatGoogleGenerativeAI # requires GOOGLE_API_KEY set as env var
5
-
6
- # Store the uploaded dataframe in memory
7
- dataframes = {}
8
-
9
- # -----------------------------
10
- # Tools (Excel Q&A Functions)
11
- # -----------------------------
12
- def get_otb_revenue(month: str) -> str:
13
- if "df" not in dataframes:
14
- return "Please upload a file first."
15
- df = dataframes["df"]
16
- try:
17
- otb = df.loc[df['Month'].str.lower() == month.lower(), 'OTB Revenue'].values[0]
18
- stly = df.loc[df['Month'].str.lower() == month.lower(), 'STLY Revenue'].values[0]
19
- return f"OTB Revenue for {month}: {otb}, STLY Revenue: {stly}"
20
- except Exception:
21
- return f"Could not find OTB/ STLY Revenue for {month}"
22
-
23
- def check_occupancy(month: str) -> str:
24
- if "df" not in dataframes:
25
- return "Please upload a file first."
26
- df = dataframes["df"]
27
- try:
28
- occ = df.loc[df['Month'].str.lower() == month.lower(), 'Occupancy %'].values[0]
29
- target = df.loc[df['Month'].str.lower() == month.lower(), 'Budgeted Occupancy %'].values[0]
30
- if occ >= target:
31
- return f"Occupancy for {month} is {occ}% vs target {target}% On track!"
32
- else:
33
- return f"Occupancy for {month} is {occ}% vs target {target}% ⚠️ Might not meet target."
34
- except Exception:
35
- return f"Could not find occupancy data for {month}"
36
-
37
- # -----------------------------
38
- # Upload Excel
39
- # -----------------------------
40
- def upload_excel(file):
41
- if file is None:
42
- return "Please upload an Excel file."
43
- dfs = pd.read_excel(file.name, sheet_name=None)
44
- dataframes.clear()
45
- dataframes.update(dfs)
46
- sheet_info = []
47
- for name, df in dfs.items():
48
- sheet_info.append(f"'{name}': {len(df)} rows, {len(df.columns)} cols")
49
- return f"✅ Loaded sheets: {', '.join(sheet_info)}"
50
-
51
- # -----------------------------
52
- # LangChain Agent Setup
53
- # -----------------------------
54
- tools = [
55
- Tool(
56
- name="Get OTB Revenue",
57
- func=get_otb_revenue,
58
- description="Get OTB Revenue and STLY Revenue for a given month (e.g. 'August')"
59
- ),
60
- Tool(
61
- name="Check Occupancy",
62
- func=check_occupancy,
63
- description="Check occupancy vs target for a given month (e.g. 'August')"
64
- )
65
- ]
66
-
67
- llm = ChatGoogleGenerativeAI(model="gemini-2.5-pro", temperature=0) # Requires GOOGLE_API_KEY in environment
68
- agent = initialize_agent(tools, llm, agent="zero-shot-react-description", verbose=True)
69
-
70
- def chat_agent(message, history):
71
- if "df" not in dataframes:
72
- return "Please upload a file first."
73
  try:
74
- return agent.run(message)
 
 
 
 
 
 
 
 
 
 
 
 
 
75
  except Exception as e:
76
- return f"⚠️ Agent error: {e}"
77
 
78
- # -----------------------------
79
- # Gradio UI
80
- # -----------------------------
81
  with gr.Blocks() as demo:
82
- gr.Markdown("# 🤖 Excel Agent (LangChain + Gemini)")
83
- with gr.Row():
84
- with gr.Column():
85
- file_input = gr.File(label="Upload Excel file", type="filepath")
86
- upload_output = gr.Textbox(label="Upload status")
87
- file_input.upload(upload_excel, file_input, upload_output)
 
 
88
 
89
- gr.ChatInterface(fn=chat_agent, title="Excel Chat Agent")
90
 
91
- demo.launch()
 
 
 
1
  import pandas as pd
2
  import gradio as gr
3
+ import os
4
+ import google.generativeai as genai # requires GOOGLE_API_KEY set as env var
5
+
6
+ # 1. Configure Gemini
7
+ genai.configure(api_key=os.getenv("GEMINI_API_KEY"))
8
+ model = genai.GenerativeModel("gemini-1.5-pro") # or "gemini-pro"
9
+
10
+ # 2. Load Excel data
11
+ df1 = pd.read_excel("report1.xlsx")
12
+ df2 = pd.read_excel("report2.xlsx")
13
+
14
+ # Build schema info for prompts
15
+ def get_schema_info():
16
+ schema1 = f"Report1 columns: {list(df1.columns)}"
17
+ schema2 = f"Report2 columns: {list(df2.columns)}"
18
+ return schema1 + "\n" + schema2
19
+
20
+ schema_info = get_schema_info()
21
+
22
+ # 3. Core function
23
+ def answer_question(history, message):
24
+ """
25
+ history: chat history (list of [user, assistant] pairs)
26
+ message: latest user message (string)
27
+ """
28
+ # Build prompt for Gemini
29
+ prompt = f"""
30
+ You are a data analysis assistant.
31
+ You can ONLY answer questions using the two Excel reports provided.
32
+ Do not hallucinate or use external knowledge.
33
+ If the question is irrelevant, respond with:
34
+ "I can only answer questions about the provided Excel reports."
35
+
36
+ The reports have the following schema:
37
+ {schema_info}
38
+
39
+ The user asked:
40
+ {message}
41
+
42
+ Generate Python pandas code that uses df1 and/or df2 to answer.
43
+ Return ONLY code, nothing else.
44
+ """
45
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
  try:
47
+ # Call Gemini
48
+ response = model.generate_content(prompt)
49
+ code = response.text.strip("```python").strip("```")
50
+
51
+ # 4. Execute code safely
52
+ local_vars = {"df1": df1, "df2": df2, "pd": pd}
53
+ try:
54
+ result = eval(code, {"__builtins__": {}}, local_vars)
55
+ except Exception as e:
56
+ exec(code, {"__builtins__": {}}, local_vars)
57
+ result = local_vars.get("result", "No result variable found")
58
+
59
+ return str(result)
60
+
61
  except Exception as e:
62
+ return f"Error: {str(e)}"
63
 
64
+
65
+ # 5. Gradio UI
 
66
  with gr.Blocks() as demo:
67
+ chatbot = gr.Chatbot()
68
+ msg = gr.Textbox(placeholder="Ask me a question about the reports...")
69
+ clear = gr.ClearButton([msg, chatbot])
70
+
71
+ def respond(message, chat_history):
72
+ answer = answer_question(chat_history, message)
73
+ chat_history.append((message, answer))
74
+ return "", chat_history
75
 
76
+ msg.submit(respond, [msg, chatbot], [msg, chatbot])
77
 
78
+ # 6. Run locally (Spaces will call demo.launch() automatically)
79
+ if __name__ == "__main__":
80
+ demo.launch()
requirements.txt CHANGED
@@ -1,5 +1,4 @@
1
  gradio==4.44.1
2
  pandas
3
  openpyxl
4
- langchain
5
- langchain-google-genai
 
1
  gradio==4.44.1
2
  pandas
3
  openpyxl
4
+ google-generativeai