PD03 commited on
Commit
0f5aca7
Β·
verified Β·
1 Parent(s): 29dd627

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +20 -54
app.py CHANGED
@@ -1,71 +1,37 @@
1
  import pandas as pd
2
- import numpy as np
3
- import re
4
- from transformers import pipeline
5
  import gradio as gr
 
 
 
6
 
7
- # Load numeric data
8
  df = pd.read_csv("synthetic_profit.csv")
9
- df_str = df.astype(str)
10
 
11
- # Initialize TAPAS
12
- qa = pipeline(
13
- "table-question-answering",
14
- model="google/tapas-base-finetuned-sqa",
15
- tokenizer="google/tapas-base-finetuned-sqa"
16
  )
17
 
18
- # Ensure column names are properly capitalized
19
- metric_columns = {"profitmargin": "ProfitMargin", "profit": "Profit",
20
- "revenue": "Revenue", "cost": "Cost"}
21
-
22
- def answer(q: str) -> str:
23
- # 1. Conditional query: negative profit
24
- if re.search(r"products.*negative.*profit", q, re.IGNORECASE):
25
- negative_profits = df[df["Profit"] < 0]
26
- if negative_profits.empty:
27
- return "βœ… No products with negative profit found."
28
- results = negative_profits[['Product', 'Region', 'FiscalQuarter', 'FiscalYear', 'Profit']]
29
- return results.to_string(index=False)
30
-
31
- # 2. Numeric summaries (total/average) – Case insensitive metric matching
32
- match = re.search(
33
- r"\b(total|average)\s+(profitmargin|profit|revenue|cost)\b.*\bProduct\s*([A-D])\b.*\b(Q[1-4])\s+(\d{4})",
34
- q, re.IGNORECASE
35
- )
36
- if match:
37
- agg_type, metric_key, product_letter, quarter, year = match.groups()
38
- metric = metric_columns[metric_key.lower()]
39
- product = f"Product {product_letter.upper()}"
40
- subset = df[
41
- (df["Product"] == product) &
42
- (df["FiscalQuarter"] == quarter) &
43
- (df["FiscalYear"] == int(year))
44
- ]
45
- if subset.empty:
46
- return "⚠️ No matching data found."
47
- if agg_type.lower() == "total":
48
- val = subset[metric].sum()
49
- else: # average
50
- val = subset[metric].mean()
51
-
52
- formatted_val = f"{val:.3f}" if metric == "ProfitMargin" else f"{val:,.2f}"
53
- return f"πŸ“Š {agg_type.title()} {metric} for {product} in {quarter} {year}: {formatted_val}"
54
 
55
- # 3. TAPAS fallback (with error handling)
56
  try:
57
- res = qa(table=df_str, query=q)
58
- return f"πŸ” {res['answer']} (agg: {res.get('aggregator','NONE')})"
59
  except Exception as e:
60
- return f"❗ Error from TAPAS: {str(e)}"
61
 
62
- # Launch Gradio
63
  demo = gr.Interface(
64
  fn=answer,
65
- inputs=gr.Textbox(lines=2, placeholder="e.g. 'total Revenue for Product B in Q1 2024?' or 'List products with negative profit.'"),
66
  outputs="text",
67
- title="🟒 SAP S/4HANA Profitability Chat",
68
- description="Ask questions on profitability data (synthetic demo). Supports total, average, and conditional queries."
69
  )
70
 
71
  demo.launch()
 
1
  import pandas as pd
 
 
 
2
  import gradio as gr
3
+ from transformers import pipeline
4
+ from langchain.llms import HuggingFacePipeline
5
+ from langchain.agents import create_pandas_dataframe_agent
6
 
7
+ # Load your data
8
  df = pd.read_csv("synthetic_profit.csv")
 
9
 
10
+ # Set up lightweight Hugging Face pipeline with Flan-T5 base
11
+ hf_pipeline = pipeline(
12
+ task="text2text-generation",
13
+ model="google/flan-t5-base",
14
+ device=-1 # ensures CPU
15
  )
16
 
17
+ # LangChain agent setup
18
+ llm = HuggingFacePipeline(pipeline=hf_pipeline)
19
+ agent = create_pandas_dataframe_agent(llm, df, verbose=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
+ def answer(query: str) -> str:
22
  try:
23
+ response = agent.run(query)
24
+ return f"πŸ“Š {response}"
25
  except Exception as e:
26
+ return f"❗ Error: {str(e)}"
27
 
28
+ # Gradio interface
29
  demo = gr.Interface(
30
  fn=answer,
31
+ inputs=gr.Textbox(lines=2, placeholder="E.g., 'Total revenue for Product B in EMEA', 'List products with negative profit.'"),
32
  outputs="text",
33
+ title="🟒 SAP Profitability Data Chat (Flan-T5 + Pandas)",
34
+ description="Ask questions about synthetic SAP profitability data. Powered by Flan-T5-base via Hugging Face."
35
  )
36
 
37
  demo.launch()