ShanukaB commited on
Commit
dd03244
·
verified ·
1 Parent(s): 69dd7a3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +74 -137
app.py CHANGED
@@ -1,141 +1,78 @@
1
- import gradio as gr
 
 
 
2
  import joblib
3
- import logging
4
  from huggingface_hub import hf_hub_download
5
- from transformers import pipeline, logging as hf_logging
6
-
7
- # ────────────────────────────────────────────────
8
- # 1. Logging Setup (Spaces compatible)
9
- # ────────────────────────────────────────────────
10
- logging.basicConfig(level=logging.INFO)
11
- hf_logging.set_verbosity_error() # reduce transformer noise
12
-
13
- logging.info("🚀 Starting application...")
14
-
15
- # ────────────────────────────────────────────────
16
- # 2. Load Models (with caching)
17
- # ────────────────────────────────────────────────
18
- @gr.cache()
19
- def load_models():
20
- try:
21
- logging.info("Loading English model...")
22
- en_vectorizer = joblib.load(
23
- hf_hub_download("E-motionAssistant/Englsih_Trained_Model_LR", "tfidf_vectorizer.joblib")
24
- )
25
- en_classifier = joblib.load(
26
- hf_hub_download("E-motionAssistant/Englsih_Trained_Model_LR", "logreg_model.joblib")
27
- )
28
- en_label_encoder = joblib.load(
29
- hf_hub_download("E-motionAssistant/Englsih_Trained_Model_LR", "label_encoder.joblib")
30
- )
31
-
32
- logging.info("Loading Sinhala model...")
33
- si_vectorizer = joblib.load(
34
- hf_hub_download("E-motionAssistant/Sinhala_Text_Emotion_Model_LR", "tfidf_vectorizer.joblib")
35
- )
36
- si_classifier = joblib.load(
37
- hf_hub_download("E-motionAssistant/Sinhala_Text_Emotion_Model_LR", "logreg_model.joblib")
38
- )
39
- si_label_encoder = joblib.load(
40
- hf_hub_download("E-motionAssistant/Sinhala_Text_Emotion_Model_LR", "label_encoder.joblib")
41
- )
42
-
43
- logging.info("Loading Tamil transformer model...")
44
- tamil_pipe = pipeline(
45
- "text-classification",
46
- model="E-motionAssistant/Tamil_Emotion_Recognition_Model"
47
- )
48
-
49
- logging.info("✅ Models loaded successfully!")
50
- return en_vectorizer, en_classifier, en_label_encoder, \
51
- si_vectorizer, si_classifier, si_label_encoder, \
52
- tamil_pipe
53
-
54
- except Exception as e:
55
- logging.error(f"❌ Model loading failed: {e}")
56
- raise e
57
-
58
-
59
- # Load once
60
- (en_vectorizer, en_classifier, en_label_encoder,
61
- si_vectorizer, si_classifier, si_label_encoder,
62
- tamil_pipe) = load_models()
63
-
64
-
65
- # ────────────────────────────────────────────────
66
- # 3. Prediction Function
67
- # ────────────────────────────────────────────────
68
- def predict_emotion(text, language):
69
- if not text.strip():
70
- return "⚠️ Please enter some text."
71
-
72
- logging.info(f"Input: {text} | Language: {language}")
73
-
74
- try:
75
- if language == "English":
76
- X = en_vectorizer.transform([text])
77
- pred = en_classifier.predict(X)[0]
78
- result = en_label_encoder.inverse_transform([pred])[0]
79
-
80
- elif language == "Sinhala":
81
- X = si_vectorizer.transform([text])
82
- pred = si_classifier.predict(X)[0]
83
- result = si_label_encoder.inverse_transform([pred])[0]
84
-
85
- elif language == "Tamil":
86
- res = tamil_pipe(text)[0]
87
- result = f"{res['label']} (Confidence: {res['score']:.3f})"
88
-
89
- logging.info(f"Prediction: {result}")
90
- return result
91
-
92
- except Exception as e:
93
- logging.error(f"Prediction error: {e}")
94
- return f"❌ Error: {str(e)}"
95
-
96
-
97
- # ────────────────────────────────────────────────
98
- # 4. Gradio UI
99
- # ────────────────────────────────────────────────
100
- with gr.Blocks(theme=gr.themes.Soft()) as demo:
101
- gr.Markdown("# 🌍 Multi-Language Emotion Detector")
102
- gr.Markdown("Select a language and enter your text to analyze the emotion.")
103
-
104
- with gr.Row():
105
- with gr.Column():
106
- input_text = gr.Textbox(
107
- label="Input Text",
108
- placeholder="Type here...",
109
- lines=3
110
- )
111
-
112
- lang_dropdown = gr.Dropdown(
113
- choices=["English", "Sinhala", "Tamil"],
114
- value="English",
115
- label="Select Language"
116
- )
117
-
118
- submit_btn = gr.Button("Analyze Emotion", variant="primary")
119
-
120
- with gr.Column():
121
- output_label = gr.Label(label="Predicted Emotion")
122
-
123
- submit_btn.click(
124
- fn=predict_emotion,
125
- inputs=[input_text, lang_dropdown],
126
- outputs=output_label
127
- )
128
-
129
- gr.Examples(
130
- examples=[
131
- ["I am very happy today!", "English"],
132
- ["මම අද ගොඩක් සතුටින්", "Sinhala"],
133
- ["நான் இன்று மிகவும் மகிழ்ச்சியாக இருக்கிறேன்", "Tamil"]
134
- ],
135
- inputs=[input_text, lang_dropdown]
136
  )
137
 
138
- # ────────────────────────────────────────────────
139
- # 5. Launch (IMPORTANT for Spaces)
140
- # ────────────────────────────────────────────────
141
- demo.launch()
 
1
+ # app.py - very simple Flask emotion detector
2
+ # English (joblib) + Sinhala & Tamil (transformers)
3
+
4
+ from flask import Flask, render_template, request
5
  import joblib
 
6
  from huggingface_hub import hf_hub_download
7
+ from transformers import pipeline
8
+
9
+ app = Flask(__name__)
10
+
11
+ print("Loading English model...")
12
+ vectorizer = joblib.load(hf_hub_download(
13
+ "E-motionAssistant/Englsih_Trained_Model_LR",
14
+ "tfidf_vectorizer.joblib"
15
+ ))
16
+ classifier = joblib.load(hf_hub_download(
17
+ "E-motionAssistant/Englsih_Trained_Model_LR",
18
+ "logreg_model.joblib"
19
+ ))
20
+ label_encoder = joblib.load(hf_hub_download(
21
+ "E-motionAssistant/Englsih_Trained_Model_LR",
22
+ "label_encoder.joblib"
23
+ ))
24
+
25
+ print("Loading Sinhala model...")
26
+ sinhala_pipe = pipeline("text-classification",
27
+ model="E-motionAssistant/Sinhala_Text_Emotion_Model_Retrained")
28
+
29
+ print("Loading Tamil model...")
30
+ tamil_pipe = pipeline("text-classification",
31
+ model="E-motionAssistant/Tamil_Emotion_Recognition_Model")
32
+
33
+ print("All models loaded successfully!")
34
+
35
+ @app.route("/", methods=["GET", "POST"])
36
+ def home():
37
+ english_result = ""
38
+ sinhala_result = ""
39
+ tamil_result = ""
40
+
41
+ if request.method == "POST":
42
+ action = request.form.get("action")
43
+
44
+ if action == "predict_english":
45
+ text = request.form.get("english_text", "").strip()
46
+ if text:
47
+ X = vectorizer.transform([text])
48
+ pred = classifier.predict(X)[0]
49
+ emotion = label_encoder.inverse_transform([pred])[0]
50
+ english_result = f"Emotion: {emotion}"
51
+ else:
52
+ english_result = "Please write something"
53
+
54
+ elif action == "predict_sinhala":
55
+ text = request.form.get("sinhala_text", "").strip()
56
+ if text:
57
+ res = sinhala_pipe(text)[0]
58
+ sinhala_result = f"හැඟීම: {res['label']} ({res['score']:.3f})"
59
+ else:
60
+ sinhala_result = "කරුණාකර යමක් ලියන්න"
61
+
62
+ elif action == "predict_tamil":
63
+ text = request.form.get("tamil_text", "").strip()
64
+ if text:
65
+ res = tamil_pipe(text)[0]
66
+ tamil_result = f"உணர்வு: {res['label']} ({res['score']:.3f})"
67
+ else:
68
+ tamil_result = "கருணையுடன் உரையை உள்ளிடவும்"
69
+
70
+ return render_template(
71
+ "index.html",
72
+ english_result=english_result,
73
+ sinhala_result=sinhala_result,
74
+ tamil_result=tamil_result
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
  )
76
 
77
+ if __name__ == "__main__":
78
+ app.run(host="0.0.0.0", port=7860, debug=False)