Spaces:
Paused
Paused
Update app.py
Browse files
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 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 62 |
|
| 63 |
-
|
| 64 |
-
|
| 65 |
|
| 66 |
-
|
| 67 |
-
|
| 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 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
result = subprocess.run(
|
| 79 |
-
[
|
| 80 |
capture_output=True,
|
| 81 |
text=True,
|
| 82 |
-
timeout=600,
|
|
|
|
| 83 |
)
|
| 84 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
if result.returncode == 0:
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
|
| 91 |
-
|
| 92 |
-
|
| 93 |
|
| 94 |
-
|
| 95 |
-
"""
|
| 96 |
else:
|
| 97 |
-
return f"""
|
| 98 |
-
β **Training failed!**
|
| 99 |
|
| 100 |
-
|
| 101 |
-
|
| 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 |
-
|
| 123 |
|
| 124 |
-
|
| 125 |
|
| 126 |
-
|
| 127 |
""")
|
| 128 |
|
| 129 |
# Status indicator
|
| 130 |
-
gr.Markdown(f"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 154 |
|
| 155 |
-
|
| 156 |
|
| 157 |
-
|
| 158 |
""")
|
| 159 |
|
| 160 |
with gr.Row():
|
|
@@ -164,24 +205,24 @@ with gr.Blocks(
|
|
| 164 |
|
| 165 |
with gr.Tab("βΉοΈ About"):
|
| 166 |
gr.Markdown("""
|
| 167 |
-
|
| 168 |
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
|
| 183 |
-
|
| 184 |
-
|
| 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
|