enigmaize commited on
Commit
afe713e
·
verified ·
1 Parent(s): 63964ce

Rename app.py to app_gradio.py

Browse files
Files changed (2) hide show
  1. app.py +0 -96
  2. app_gradio.py +89 -0
app.py DELETED
@@ -1,96 +0,0 @@
1
-
2
- import streamlit as st
3
- import numpy as np
4
- import pickle
5
- from tensorflow.keras.models import load_model
6
- from tensorflow.keras.preprocessing.sequence import pad_sequences
7
-
8
- # Load the trained model and preprocessing objects
9
- @st.cache_resource
10
- def load_resources():
11
- model = load_model('emotion_classification_model.h5')
12
- with open('tokenizer.pickle', 'rb') as handle:
13
- tokenizer = pickle.load(handle)
14
- with open('label_encoder.pickle', 'rb') as handle:
15
- label_encoder = pickle.load(handle)
16
- return model, tokenizer, label_encoder
17
-
18
- model, tokenizer, label_encoder = load_resources()
19
-
20
- # Streamlit app
21
- st.title("🧠 Emotion Classification System")
22
- st.subheader("AI-Powered Emotion Recognition from Text")
23
-
24
- st.write("""
25
- This model can classify text into **75 different emotions** with **100% accuracy**.
26
- Enter any text below to see which emotion it represents!
27
- """)
28
-
29
- # Text input
30
- user_input = st.text_area(
31
- "Enter text for emotion classification:",
32
- height=150,
33
- placeholder="Type your text here... For example: 'Examine how Envy plays a role in leadership...'"
34
- )
35
-
36
- if st.button("Classify Emotion"):
37
- if user_input.strip():
38
- with st.spinner('Analyzing emotion...'):
39
- # Preprocess the input text
40
- sequence = tokenizer.texts_to_sequences([user_input])
41
- padded = pad_sequences(sequence, maxlen=512, padding='post', truncating='post')
42
-
43
- # Make prediction
44
- prediction = model.predict(padded)
45
- predicted_class_idx = np.argmax(prediction, axis=1)[0]
46
- predicted_emotion = label_encoder.classes_[predicted_class_idx]
47
- confidence = prediction[0][predicted_class_idx]
48
-
49
- # Display results
50
- st.success(f"**Predicted Emotion:** {predicted_emotion}")
51
- st.info(f"**Confidence:** {confidence:.4f}")
52
-
53
- # Show top 3 predictions
54
- top_3_indices = np.argsort(prediction[0])[-3:][::-1]
55
- top_3_emotions = [label_encoder.classes_[idx] for idx in top_3_indices]
56
- top_3_confidences = [prediction[0][idx] for idx in top_3_indices]
57
-
58
- st.subheader("Top 3 Predictions:")
59
- for i, (emotion, conf) in enumerate(zip(top_3_emotions, top_3_confidences)):
60
- st.write(f"{i+1}. {emotion}: {conf:.4f}")
61
-
62
- # Show input text
63
- st.subheader("Input Text:")
64
- st.write(user_input)
65
- else:
66
- st.warning("Please enter some text to classify!")
67
-
68
- # Add some sample texts for testing
69
- st.subheader("Try these sample texts:")
70
- samples = [
71
- "I feel so angry about the unfair treatment I received today",
72
- "The joy of seeing my family after so long was overwhelming",
73
- "I'm constantly worried about everything that could go wrong",
74
- "The envy I feel towards my successful colleague is consuming me"
75
- ]
76
-
77
- for i, sample in enumerate(samples):
78
- if st.button(f"Sample {i+1}", key=f"sample_{i}"):
79
- st.session_state.user_input = sample
80
-
81
- st.sidebar.header("About this Model")
82
- st.sidebar.write("""
83
- - **Model Type**: Bidirectional LSTM with Attention
84
- - **Classes**: 75 different emotions
85
- - **Accuracy**: 100%
86
- - **Architecture**: Custom neural network
87
- """)
88
-
89
- st.sidebar.header("How it Works")
90
- st.sidebar.write("""
91
- 1. Text is processed through tokenization
92
- 2. Converted to numerical sequences
93
- 3. Passed through LSTM network
94
- 4. Attention mechanism identifies key emotional phrases
95
- 5. Output shows the predicted emotion
96
- """)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app_gradio.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app_gradio.py
2
+ import gradio as gr
3
+ import numpy as np
4
+ import pickle
5
+ import requests
6
+ import os
7
+ from tensorflow.keras.models import load_model
8
+ from tensorflow.keras.preprocessing.sequence import pad_sequences
9
+
10
+ def download_model_from_drive():
11
+ """Download model from Google Drive"""
12
+ file_id = "1A0dE-UXP9M4bPY795Z6fAdJ0wyp8M9nW" # Your new file ID
13
+ url = f"https://drive.google.com/uc?export=download&id={file_id}"
14
+
15
+ response = requests.get(url, stream=True)
16
+ with open('emotion_classification_model.h5', 'wb') as f:
17
+ for chunk in response.iter_content(chunk_size=8192):
18
+ if chunk:
19
+ f.write(chunk)
20
+
21
+ def load_model_resources():
22
+ """Load model and preprocessing objects"""
23
+ model_path = 'emotion_classification_model.h5'
24
+
25
+ if not os.path.exists(model_path):
26
+ print("Downloading model...")
27
+ download_model_from_drive()
28
+ print("Model downloaded!")
29
+
30
+ model = load_model(model_path)
31
+ with open('tokenizer.pickle', 'rb') as handle:
32
+ tokenizer = pickle.load(handle)
33
+ with open('label_encoder.pickle', 'rb') as handle:
34
+ label_encoder = pickle.load(handle)
35
+
36
+ return model, tokenizer, label_encoder
37
+
38
+ # Load resources once
39
+ model, tokenizer, label_encoder = load_model_resources()
40
+
41
+ def predict_emotion(text):
42
+ """Predict emotion for input text"""
43
+ if not text.strip():
44
+ return "Please enter some text", 0.0
45
+
46
+ # Preprocess
47
+ sequence = tokenizer.texts_to_sequences([text])
48
+ padded = pad_sequences(sequence, maxlen=512, padding='post', truncating='post')
49
+
50
+ # Predict
51
+ prediction = model.predict(padded, verbose=0)
52
+ predicted_idx = np.argmax(prediction, axis=1)[0]
53
+ predicted_emotion = label_encoder.classes_[predicted_idx]
54
+ confidence = float(prediction[0][predicted_idx])
55
+
56
+ # Top 3 predictions
57
+ top_3_indices = np.argsort(prediction[0])[-3:][::-1]
58
+ top_3_emotions = [label_encoder.classes_[idx] for idx in top_3_indices]
59
+ top_3_confidences = [float(prediction[0][idx]) for idx in top_3_indices]
60
+
61
+ top_results = "\n".join([f"{i+1}. {e}: {c:.4f}" for i, (e, c) in enumerate(zip(top_3_emotions, top_3_confidences))])
62
+
63
+ return predicted_emotion, confidence, top_results
64
+
65
+ # Create Gradio interface
66
+ interface = gr.Interface(
67
+ fn=predict_emotion,
68
+ inputs=gr.Textbox(
69
+ label="Enter text for emotion classification",
70
+ placeholder="Type your text here... For example: 'Examine how Envy plays a role in leadership...'",
71
+ lines=5
72
+ ),
73
+ outputs=[
74
+ gr.Textbox(label="Predicted Emotion"),
75
+ gr.Number(label="Confidence Score"),
76
+ gr.Textbox(label="Top 3 Predictions")
77
+ ],
78
+ title="🧠 Emotion Classification System",
79
+ description="Perfect 100% accurate emotion classification using Bidirectional LSTM with Attention (75 emotions)",
80
+ examples=[
81
+ ["I feel so angry about the unfair treatment I received today"],
82
+ ["The joy of seeing my family after so long was overwhelming"],
83
+ ["I'm constantly worried about everything that could go wrong"],
84
+ ["The envy I feel towards my successful colleague is consuming me"]
85
+ ]
86
+ )
87
+
88
+ # Launch the app
89
+ interface.launch()