ktr008 commited on
Commit
c522fb1
·
verified ·
1 Parent(s): 64e7b75

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +44 -0
app.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import numpy as np
3
+ from transformers import AutoModelForSequenceClassification, AutoTokenizer, AutoConfig
4
+ from scipy.special import softmax
5
+
6
+ # Load fine-tuned model and tokenizer
7
+ MODEL_PATH = "" # Ensure the model is uploaded to Hugging Face
8
+ model = AutoModelForSequenceClassification.from_pretrained(MODEL_PATH)
9
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH)
10
+ config = AutoConfig.from_pretrained(MODEL_PATH)
11
+
12
+ # Preprocess function
13
+ def preprocess(text):
14
+ new_text = []
15
+ for t in text.split(" "):
16
+ t = '@user' if t.startswith('@') and len(t) > 1 else t
17
+ t = 'http' if t.startswith('http') else t
18
+ new_text.append(t)
19
+ return " ".join(new_text)
20
+
21
+ # Prediction function
22
+ def predict_sentiment(text):
23
+ text = preprocess(text)
24
+ encoded_input = tokenizer(text, return_tensors='pt')
25
+ output = model(**encoded_input)
26
+ scores = output[0][0].detach().numpy()
27
+ scores = softmax(scores)
28
+
29
+ # Get sentiment labels and scores
30
+ ranking = np.argsort(scores)[::-1]
31
+ result = {config.id2label[ranking[i]]: round(float(scores[ranking[i]]) * 100, 2) for i in range(scores.shape[0])}
32
+ return result
33
+
34
+ # Gradio Interface
35
+ interface = gr.Interface(
36
+ fn=predict_sentiment,
37
+ inputs=gr.Textbox(lines=3, placeholder="Enter text..."),
38
+ outputs=gr.Label(),
39
+ title="Fine-Tuned Sentiment Analysis",
40
+ description="Enter a sentence to analyze its sentiment (Positive, Neutral, Negative).",
41
+ )
42
+
43
+ # Launch the app
44
+ interface.launch()