rawsun007 commited on
Commit
323e55b
·
1 Parent(s): 7a94bba

code update in app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -42
app.py CHANGED
@@ -8,19 +8,21 @@ import uvicorn
8
 
9
  MODEL_ID = "rawsun00001/banking-sms-json-parser-v6-merged"
10
 
11
- print("🔄 Loading banking‑SMS JSON parser model...")
 
 
12
  tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
13
  model = AutoModelForCausalLM.from_pretrained(
14
  MODEL_ID,
15
  torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
16
- device_map="auto" if torch.cuda.is_available() else None,
17
  )
18
  if tokenizer.pad_token is None:
19
  tokenizer.pad_token = tokenizer.eos_token
20
- print("✅ Model loaded")
21
 
22
- def parse_banking_sms(raw_text: str) -> dict:
23
- sms = " ".join(raw_text.strip().split())
 
24
  prompt = sms + "|"
25
  inputs = tokenizer(prompt, return_tensors="pt")
26
  if torch.cuda.is_available():
@@ -32,14 +34,14 @@ def parse_banking_sms(raw_text: str) -> dict:
32
  do_sample=False,
33
  repetition_penalty=1.05,
34
  pad_token_id=tokenizer.eos_token_id,
35
- eos_token_id=tokenizer.eos_token_id,
36
  )
37
  decoded = tokenizer.decode(outputs[0], skip_special_tokens=True)
38
  json_part = decoded[len(prompt):].strip()
39
- m = re.search(r"\{[^{}]+\}", json_part)
40
- if m:
41
  try:
42
- parsed = json.loads(m.group())
43
  return {
44
  "date": parsed.get("date"),
45
  "type": parsed.get("type"),
@@ -51,52 +53,66 @@ def parse_banking_sms(raw_text: str) -> dict:
51
  except json.JSONDecodeError:
52
  pass
53
  return {
54
- "date": None,
55
- "type": None,
56
- "amount": None,
57
- "category": None,
58
- "last4": None,
59
- "is_transaction": False,
60
  }
61
 
62
- def chatbot_response(user_message, history):
63
- # Check if history is a list, else initialize empty list
 
64
  if not isinstance(history, list):
65
  history = []
66
-
67
- result = parse_banking_sms(user_message)
68
- if result["is_transaction"]:
69
- response = (
70
  f"✅ Transaction Detected!\n\n"
71
- f"📅 Date: {result['date']}\n"
72
- f"💳 Type: {result['type'].title() if result['type'] else 'N/A'}\n"
73
- f"💰 Amount: {result['amount']}\n"
74
- f"🏪 Category: {result['category']}\n"
75
- f"🔢 Last 4 Digits: {result['last4']}"
 
76
  )
77
  else:
78
- response = ("ℹ️ Non-Transaction Message\n\n"
79
- "This looks like a promo or info message.")
80
-
81
- history.append({"role": "user", "content": user_message})
82
- history.append({"role": "assistant", "content": response})
 
 
 
 
 
83
  return history, ""
84
 
 
 
 
 
85
  with gr.Blocks() as demo:
86
- gr.Markdown(
87
- """
88
- ## 🏦 Banking SMS JSON Parser Chatbot
 
 
89
 
90
- Paste your banking SMS here — the app will detect whether it's a transaction
91
- and extract date, amount, merchant, etc.
92
- """
 
 
 
 
93
  )
94
- chatbot = gr.Chatbot(type="messages", label="Parser Bot", height=400, value=[]) # initial empty list
95
- msg = gr.Textbox(lines=3, label="Your SMS message")
96
- msg.submit(chatbot_response, inputs=[msg, chatbot], outputs=[chatbot, msg])
97
- msg.submit(lambda: "", None, msg)
98
- gr.Markdown(f"\n---\n**Backend model:** `{MODEL_ID}`")
99
 
 
 
 
100
  app = FastAPI()
101
  app.mount("/", demo)
102
 
 
8
 
9
  MODEL_ID = "rawsun00001/banking-sms-json-parser-v6-merged"
10
 
11
+ # -------------------------------
12
+ # 1. Load model & tokenizer
13
+ # -------------------------------
14
  tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
15
  model = AutoModelForCausalLM.from_pretrained(
16
  MODEL_ID,
17
  torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
18
+ device_map="auto" if torch.cuda.is_available() else None
19
  )
20
  if tokenizer.pad_token is None:
21
  tokenizer.pad_token = tokenizer.eos_token
 
22
 
23
+
24
+ def parse_banking_sms(raw_text):
25
+ sms = " ".join(raw_text.split())
26
  prompt = sms + "|"
27
  inputs = tokenizer(prompt, return_tensors="pt")
28
  if torch.cuda.is_available():
 
34
  do_sample=False,
35
  repetition_penalty=1.05,
36
  pad_token_id=tokenizer.eos_token_id,
37
+ eos_token_id=tokenizer.eos_token_id
38
  )
39
  decoded = tokenizer.decode(outputs[0], skip_special_tokens=True)
40
  json_part = decoded[len(prompt):].strip()
41
+ match = re.search(r"\{[^{}]+\}", json_part)
42
+ if match:
43
  try:
44
+ parsed = json.loads(match.group())
45
  return {
46
  "date": parsed.get("date"),
47
  "type": parsed.get("type"),
 
53
  except json.JSONDecodeError:
54
  pass
55
  return {
56
+ "date": None, "type": None, "amount": None,
57
+ "category": None, "last4": None, "is_transaction": False
 
 
 
 
58
  }
59
 
60
+
61
+ def chatbot_response(user_msg, history):
62
+ # 🛠 Fix: history must always be a list (Gradio v5 validation expects list of dicts)
63
  if not isinstance(history, list):
64
  history = []
65
+
66
+ res = parse_banking_sms(user_msg)
67
+ if res["is_transaction"]:
68
+ assistant_msg = (
69
  f"✅ Transaction Detected!\n\n"
70
+ f"📅 Date: {res['date']}\n"
71
+ f"💳 Type: {res['type'].title() if res['type'] else 'N/A'}\n"
72
+ f"💰 Amount: {res['amount']}\n"
73
+ f"🏪 Category: {res['category']}\n"
74
+ f"🔢 Last 4 Digits: {res['last4']}\n\n"
75
+ f"**Full JSON:**\n```json\n{json.dumps(res, indent=2)}\n```"
76
  )
77
  else:
78
+ assistant_msg = (
79
+ "ℹ️ Non-Transaction Message\n\n"
80
+ "This appears to be a promotional or informational SMS or email.\n\n"
81
+ f"**Classification JSON:**\n```json\n{json.dumps(res, indent=2)}\n```"
82
+ )
83
+
84
+ # Update history
85
+ history.append({"role": "user", "content": user_msg})
86
+ history.append({"role": "assistant", "content": assistant_msg})
87
+
88
  return history, ""
89
 
90
+
91
+ # -------------------------------
92
+ # 4. Gradio UI
93
+ # -------------------------------
94
  with gr.Blocks() as demo:
95
+ gr.Markdown("""
96
+ ## 🏦 Banking SMS JSON Parser
97
+
98
+ Paste your banking SMS or email below. The bot will extract structured transaction JSON.
99
+ """)
100
 
101
+ chatbot_ui = gr.Chatbot(type="messages", value=[])
102
+ msg_txt = gr.Textbox(lines=3, placeholder="Paste SMS here…", label="Input SMS")
103
+
104
+ msg_txt.submit(
105
+ fn=chatbot_response,
106
+ inputs=[msg_txt, chatbot_ui],
107
+ outputs=[chatbot_ui, msg_txt]
108
  )
109
+ msg_txt.submit(lambda _: "", None, msg_txt)
110
+
111
+ gr.Markdown(f"---\n**Model ID:** `{MODEL_ID}`")
 
 
112
 
113
+ # -------------------------------
114
+ # 5. Mount with FastAPI
115
+ # -------------------------------
116
  app = FastAPI()
117
  app.mount("/", demo)
118