Surajnitp commited on
Commit
21f7535
Β·
verified Β·
1 Parent(s): 3399a22

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +95 -54
app.py CHANGED
@@ -7,6 +7,7 @@ import gradio as gr
7
  from transformers import pipeline
8
  import subprocess
9
  import os
 
10
 
11
  # Global variable to store the classifier
12
  classifier = None
@@ -37,18 +38,24 @@ def load_model():
37
 
38
  except Exception as e:
39
  # Fall back to default model
40
- classifier = pipeline(
41
- "sentiment-analysis",
42
- model="distilbert-base-uncased-finetuned-sst-2-english",
43
- )
44
- return f"⚠️ Using default model (fine-tuned model not found): {str(e)}"
 
 
 
45
 
46
 
47
  def predict(text):
48
  """Predict sentiment of input text"""
49
- if not text.strip():
50
  return "⚠️ Please enter some text to analyze."
51
 
 
 
 
52
  try:
53
  result = classifier(text)
54
  label = result[0]['label']
@@ -58,54 +65,85 @@ def predict(text):
58
  emoji = "😊" if label == "POSITIVE" else "😞"
59
 
60
  return f"""
61
- ### πŸ“Š Sentiment Analysis Result
62
 
63
- {emoji} **Label:** {label}
64
- 🎯 **Confidence:** {score:.2%}
65
 
66
- ---
67
- πŸ“ **Text analyzed:** "{text[:100]}..."
68
- """
69
 
70
  except Exception as e:
71
- return f"❌ Error: {str(e)}"
72
 
73
 
74
  def run_training():
75
  """Run the training script and return status"""
76
  try:
77
- # Run the training script
 
 
 
 
78
  result = subprocess.run(
79
- ["python", "train.py"],
80
  capture_output=True,
81
  text=True,
82
- timeout=600, # 10 minute timeout
 
83
  )
84
 
 
 
 
 
 
 
 
85
  if result.returncode == 0:
86
- # Reload the model after training
87
- load_model()
88
- return f"""
89
- βœ… **Training completed successfully!**
 
 
 
 
 
 
 
 
 
90
 
91
- πŸ“Š **Output:**
92
- {result.stdout[:500]}...
93
 
94
- 🎯 The model has been saved to `./my_finetuned_model`
95
- """
96
  else:
97
- return f"""
98
- ❌ **Training failed!**
99
 
100
- πŸ“Š **Error:**
101
- {result.stderr[:500]}...
102
- """
 
 
 
 
103
 
104
  except subprocess.TimeoutExpired:
105
- return "⏰ Training timed out after 10 minutes."
 
 
 
 
 
 
 
 
106
 
107
  except Exception as e:
108
- return f"❌ Unexpected error: {str(e)}"
109
 
110
 
111
  # Load the model on startup
@@ -115,19 +153,23 @@ load_status = load_model()
115
  with gr.Blocks(
116
  title="Trackmodel - Sentiment Analysis",
117
  theme=gr.themes.Soft(),
118
- css=".gradio-container {max-width: 800px; margin: auto;}"
119
  ) as demo:
120
 
121
  gr.Markdown("""
122
- # 🎯 Trackmodel - Sentiment Analysis
123
 
124
- This Space demonstrates downloading, fine-tuning, and deploying models on Hugging Face.
125
 
126
- **Model:** DistilBERT fine-tuned on IMDb reviews for sentiment classification.
127
  """)
128
 
129
  # Status indicator
130
- gr.Markdown(f"**Status:** {load_status}")
 
 
 
 
131
 
132
  with gr.Tab("πŸ’¬ Predict"):
133
  gr.Markdown("### Enter text to analyze sentiment")
@@ -144,17 +186,16 @@ with gr.Blocks(
144
  clear_btn = gr.Button("πŸ—‘οΈ Clear", variant="secondary")
145
 
146
  output = gr.Markdown(
147
- label="Result",
148
  value="πŸ“ Enter text and click 'Predict' to see results.",
149
  )
150
 
151
  with gr.Tab("βš™οΈ Training"):
152
  gr.Markdown("""
153
- ### Train the Model on Custom Data
154
 
155
- Click the button below to fine-tune the model on the IMDb dataset.
156
 
157
- ⚠️ **Note:** This will take ~3-5 minutes on a CPU instance.
158
  """)
159
 
160
  with gr.Row():
@@ -164,24 +205,24 @@ with gr.Blocks(
164
 
165
  with gr.Tab("ℹ️ About"):
166
  gr.Markdown("""
167
- ## About Trackmodel
168
 
169
- ### What this Space does:
170
- 1. **Downloads** a pre-trained DistilBERT model
171
- 2. **Fine-tunes** it on the IMDb movie review dataset
172
- 3. **Deploys** the trained model as a web app
173
 
174
- ### How to use:
175
- - Go to the **Predict** tab to analyze text sentiment
176
- - Go to the **Training** tab to fine-tune the model yourself
177
 
178
- ### Links:
179
- - [Hugging Face Models](https://huggingface.co/models)
180
- - [Gradio Documentation](https://gradio.app/docs)
181
- - [Hugging Face Course](https://huggingface.co/learn/nlp-course)
182
 
183
- ### Author:
184
- **Surajnitp** πŸš€
185
  """)
186
 
187
  # Connect event handlers
 
7
  from transformers import pipeline
8
  import subprocess
9
  import os
10
+ import sys
11
 
12
  # Global variable to store the classifier
13
  classifier = None
 
38
 
39
  except Exception as e:
40
  # Fall back to default model
41
+ try:
42
+ classifier = pipeline(
43
+ "sentiment-analysis",
44
+ model="distilbert-base-uncased-finetuned-sst-2-english",
45
+ )
46
+ return f"⚠️ Using default model (fine-tuned model not found): {str(e)}"
47
+ except Exception as e2:
48
+ return f"❌ CRITICAL: Could not load any model: {str(e2)}"
49
 
50
 
51
  def predict(text):
52
  """Predict sentiment of input text"""
53
+ if not text or not text.strip():
54
  return "⚠️ Please enter some text to analyze."
55
 
56
+ if classifier is None:
57
+ return "❌ Model not loaded. Please restart the app."
58
+
59
  try:
60
  result = classifier(text)
61
  label = result[0]['label']
 
65
  emoji = "😊" if label == "POSITIVE" else "😞"
66
 
67
  return f"""
68
+ ### πŸ“Š Sentiment Analysis Result
69
 
70
+ {emoji} **Label:** {label}
71
+ 🎯 **Confidence:** {score:.2%}
72
 
73
+ ---
74
+ πŸ“ **Text analyzed:** "{text[:100]}{'...' if len(text) > 100 else ''}"
75
+ """
76
 
77
  except Exception as e:
78
+ return f"❌ Error during prediction: {str(e)}"
79
 
80
 
81
  def run_training():
82
  """Run the training script and return status"""
83
  try:
84
+ # Check if train.py exists
85
+ if not os.path.exists("train.py"):
86
+ return "❌ Training script not found! The file `train.py` is missing from this Space. Please add it and try again."
87
+
88
+ # Run the training script with full output capture
89
  result = subprocess.run(
90
+ [sys.executable, "train.py"],
91
  capture_output=True,
92
  text=True,
93
+ timeout=600,
94
+ env=os.environ.copy(),
95
  )
96
 
97
+ # Combine stdout and stderr for full output
98
+ full_output = result.stdout + result.stderr
99
+
100
+ # Truncate if too long
101
+ if len(full_output) > 3000:
102
+ full_output = full_output[:3000] + "\n... (output truncated)"
103
+
104
  if result.returncode == 0:
105
+ if os.path.exists("./my_finetuned_model"):
106
+ load_status = load_model()
107
+ return f"""βœ… Training completed successfully!
108
+
109
+ Full Output:
110
+ {full_output}
111
+
112
+ Model saved to: ./my_finetuned_model
113
+ Status: {load_status}
114
+
115
+ Try the Predict tab now with your custom model!"""
116
+ else:
117
+ return f"""⚠️ Training completed but model not found!
118
 
119
+ Output:
120
+ {full_output}
121
 
122
+ The model should be at ./my_finetuned_model but it's missing."""
 
123
  else:
124
+ return f"""❌ Training failed! (Exit code: {result.returncode})
 
125
 
126
+ Full Error Output:
127
+ {full_output}
128
+
129
+ Troubleshooting tips:
130
+ 1. Check if torch is installed: pip list | grep torch
131
+ 2. Check if datasets is installed: pip list | grep datasets
132
+ 3. Try running training from terminal: python train.py"""
133
 
134
  except subprocess.TimeoutExpired:
135
+ return """⏰ Training timed out after 10 minutes!
136
+
137
+ The training is taking too long. Try:
138
+ 1. Using a smaller dataset (modify select(range(100)) in train.py)
139
+ 2. Reducing epochs (change num_train_epochs=1)
140
+ 3. Using a GPU instance (if available)"""
141
+
142
+ except FileNotFoundError:
143
+ return "❌ Python not found! The system cannot find the Python interpreter."
144
 
145
  except Exception as e:
146
+ return f"❌ Unexpected error during training: {str(e)}"
147
 
148
 
149
  # Load the model on startup
 
153
  with gr.Blocks(
154
  title="Trackmodel - Sentiment Analysis",
155
  theme=gr.themes.Soft(),
156
+ css=".gradio-container {max-width: 800px; margin: auto;} .status-box {padding: 10px; border-radius: 5px; background: #f0f0f0;}"
157
  ) as demo:
158
 
159
  gr.Markdown("""
160
+ # 🎯 Trackmodel - Sentiment Analysis
161
 
162
+ This Space demonstrates downloading, fine-tuning, and deploying models on Hugging Face.
163
 
164
+ **Model:** DistilBERT fine-tuned on IMDb reviews for sentiment classification.
165
  """)
166
 
167
  # Status indicator
168
+ gr.Markdown(f"""
169
+ <div class="status-box">
170
+ **Status:** {load_status}
171
+ </div>
172
+ """)
173
 
174
  with gr.Tab("πŸ’¬ Predict"):
175
  gr.Markdown("### Enter text to analyze sentiment")
 
186
  clear_btn = gr.Button("πŸ—‘οΈ Clear", variant="secondary")
187
 
188
  output = gr.Markdown(
 
189
  value="πŸ“ Enter text and click 'Predict' to see results.",
190
  )
191
 
192
  with gr.Tab("βš™οΈ Training"):
193
  gr.Markdown("""
194
+ ### Train the Model on Custom Data
195
 
196
+ Click the button below to fine-tune the model on the IMDb dataset.
197
 
198
+ ⚠️ **Note:** This will take ~3-5 minutes on a CPU instance.
199
  """)
200
 
201
  with gr.Row():
 
205
 
206
  with gr.Tab("ℹ️ About"):
207
  gr.Markdown("""
208
+ ## About Trackmodel
209
 
210
+ ### What this Space does:
211
+ 1. **Downloads** a pre-trained DistilBERT model
212
+ 2. **Fine-tunes** it on the IMDb movie review dataset
213
+ 3. **Deploys** the trained model as a web app
214
 
215
+ ### How to use:
216
+ - Go to the **Predict** tab to analyze text sentiment
217
+ - Go to the **Training** tab to fine-tune the model yourself
218
 
219
+ ### Links:
220
+ - [Hugging Face Models](https://huggingface.co/models)
221
+ - [Gradio Documentation](https://gradio.app/docs)
222
+ - [Hugging Face Course](https://huggingface.co/learn/nlp-course)
223
 
224
+ ### Author:
225
+ **Surajnitp** πŸš€
226
  """)
227
 
228
  # Connect event handlers