gopichandra commited on
Commit
3b6b8a6
Β·
verified Β·
1 Parent(s): 34cfb2f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +31 -28
app.py CHANGED
@@ -1,48 +1,51 @@
 
1
  import gradio as gr
2
  import joblib
3
- import torch
4
  from transformers import AutoTokenizer, AutoModelForSequenceClassification
 
5
 
6
- # βœ… Use folder name directly (no ./)
7
- model_dir = "campaign-bert-model"
 
 
 
 
 
8
 
 
9
  try:
10
  tokenizer = AutoTokenizer.from_pretrained(model_dir, use_fast=False)
11
  model = AutoModelForSequenceClassification.from_pretrained(model_dir)
12
- label_encoder = joblib.load("label_encoder.pkl")
13
- print("βœ… Model, Tokenizer, and Label Encoder loaded.")
14
  except Exception as e:
15
  raise RuntimeError(f"❌ Failed to load model or tokenizer: {e}")
16
 
17
- # βœ… Prediction logic
18
  def predict(client_interest, sentiment):
19
  try:
20
  text = f"{client_interest} Sentiment: {sentiment}"
21
  inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True)
22
- outputs = model(**inputs)
23
- predicted_id = torch.argmax(outputs.logits, dim=1).item()
24
- label = label_encoder.inverse_transform([predicted_id])[0]
25
- confidence = torch.softmax(outputs.logits, dim=1)[0][predicted_id].item()
26
- return f"🎯 Template: **{label}**\nπŸ“Š Confidence: **{confidence:.2%}**"
27
- except Exception as err:
28
- return f"❌ Prediction failed: {err}"
29
-
30
- # βœ… UI with styling
31
- with gr.Blocks(theme=gr.themes.Soft()) as demo:
32
- gr.Markdown("## 🎯 Campaign Personalizer")
33
- gr.Markdown("Provide interest and sentiment to get the best marketing template.")
34
-
35
  with gr.Row():
36
- with gr.Column():
37
- interest = gr.Textbox(label="πŸ“ Client Interest")
38
- sentiment = gr.Textbox(label="😊 Sentiment")
39
- submit = gr.Button("πŸ” Predict")
40
- with gr.Column():
41
- result = gr.Markdown(label="🎯 Output")
42
 
43
- submit.click(predict, inputs=[interest, sentiment], outputs=result)
44
 
45
- # βœ… Launch app
46
  if __name__ == "__main__":
47
  demo.launch()
48
-
 
1
+ import os
2
  import gradio as gr
3
  import joblib
 
4
  from transformers import AutoTokenizer, AutoModelForSequenceClassification
5
+ import torch
6
 
7
+ # βœ… Detect environment and set paths
8
+ if os.path.exists("/home/user/app"):
9
+ model_dir = "campaign-bert-model" # Hugging Face Space
10
+ label_path = "label_encoder.pkl"
11
+ else:
12
+ model_dir = r"C:\Users\gopic\campaign_bert_model\campaign_bert_model\campaign-bert-model"
13
+ label_path = r"C:\Users\gopic\campaign_bert_model\campaign_bert_model\label_encoder.pkl"
14
 
15
+ # βœ… Load tokenizer, model, and label encoder
16
  try:
17
  tokenizer = AutoTokenizer.from_pretrained(model_dir, use_fast=False)
18
  model = AutoModelForSequenceClassification.from_pretrained(model_dir)
19
+ label_encoder = joblib.load(label_path)
 
20
  except Exception as e:
21
  raise RuntimeError(f"❌ Failed to load model or tokenizer: {e}")
22
 
23
+ # βœ… Define prediction function
24
  def predict(client_interest, sentiment):
25
  try:
26
  text = f"{client_interest} Sentiment: {sentiment}"
27
  inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True)
28
+ with torch.no_grad():
29
+ outputs = model(**inputs)
30
+ logits = outputs.logits
31
+ prediction = torch.argmax(logits, dim=1).item()
32
+ template = label_encoder.inverse_transform([prediction])[0]
33
+ confidence = torch.softmax(logits, dim=1)[0][prediction].item()
34
+ return f"πŸ“„ Suggested Template: {template}\nπŸ” Confidence: {confidence:.2%}"
35
+ except Exception as e:
36
+ return f"❌ Error in prediction: {e}"
37
+
38
+ # βœ… Build Gradio UI
39
+ with gr.Blocks(css=".gradio-container {background: #f0f4f8;}") as demo:
40
+ gr.Markdown("<h1 style='text-align: center; color: #1f2937;'>πŸ“’ Campaign Personalizer</h1>")
41
  with gr.Row():
42
+ client_interest = gr.Textbox(label="Client Interest", placeholder="e.g. Term Insurance for family", lines=2)
43
+ sentiment = gr.Textbox(label="Sentiment", placeholder="e.g. Positive", lines=2)
44
+ predict_btn = gr.Button("πŸ” Predict Template")
45
+ output = gr.Textbox(label="Prediction Result")
 
 
46
 
47
+ predict_btn.click(fn=predict, inputs=[client_interest, sentiment], outputs=output)
48
 
49
+ # βœ… Launch
50
  if __name__ == "__main__":
51
  demo.launch()