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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Trackmodel - Gradio Web App
|
| 3 |
+
This app loads your fine-tuned model and provides a web interface
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
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
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def load_model():
|
| 16 |
+
"""Load the fine-tuned model"""
|
| 17 |
+
global classifier
|
| 18 |
+
|
| 19 |
+
try:
|
| 20 |
+
# Try loading from local first
|
| 21 |
+
if os.path.exists("./my_finetuned_model"):
|
| 22 |
+
classifier = pipeline(
|
| 23 |
+
"sentiment-analysis",
|
| 24 |
+
model="./my_finetuned_model",
|
| 25 |
+
tokenizer="./my_finetuned_model",
|
| 26 |
+
)
|
| 27 |
+
return "โ
Loaded fine-tuned model from local"
|
| 28 |
+
|
| 29 |
+
# Fall back to Hugging Face Hub
|
| 30 |
+
model_name = "Surajnitp/sentiment-trackmodel"
|
| 31 |
+
classifier = pipeline(
|
| 32 |
+
"sentiment-analysis",
|
| 33 |
+
model=model_name,
|
| 34 |
+
tokenizer=model_name,
|
| 35 |
+
)
|
| 36 |
+
return f"โ
Loaded model from Hub: {model_name}"
|
| 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']
|
| 55 |
+
score = result[0]['score']
|
| 56 |
+
|
| 57 |
+
# Emoji for visual feedback
|
| 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
|
| 112 |
+
load_status = load_model()
|
| 113 |
+
|
| 114 |
+
# Create the Gradio interface
|
| 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")
|
| 134 |
+
|
| 135 |
+
with gr.Row():
|
| 136 |
+
with gr.Column(scale=4):
|
| 137 |
+
text_input = gr.Textbox(
|
| 138 |
+
label="Your text",
|
| 139 |
+
placeholder="Type something like: 'I love this movie!'",
|
| 140 |
+
lines=4,
|
| 141 |
+
)
|
| 142 |
+
with gr.Column(scale=1):
|
| 143 |
+
predict_btn = gr.Button("๐ฎ Predict", variant="primary", size="lg")
|
| 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():
|
| 161 |
+
train_btn = gr.Button("๐ Start Training", variant="primary", size="lg")
|
| 162 |
+
|
| 163 |
+
train_output = gr.Markdown("โน๏ธ Click the button to start training.")
|
| 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
|
| 188 |
+
predict_btn.click(fn=predict, inputs=text_input, outputs=output)
|
| 189 |
+
clear_btn.click(fn=lambda: "", inputs=None, outputs=text_input)
|
| 190 |
+
clear_btn.click(
|
| 191 |
+
fn=lambda: "๐ Enter text and click 'Predict' to see results.",
|
| 192 |
+
inputs=None,
|
| 193 |
+
outputs=output
|
| 194 |
+
)
|
| 195 |
+
train_btn.click(fn=run_training, inputs=None, outputs=train_output)
|
| 196 |
+
|
| 197 |
+
# Launch the app
|
| 198 |
+
if __name__ == "__main__":
|
| 199 |
+
demo.launch()
|