abdullah123456 commited on
Commit
edccab1
·
verified ·
1 Parent(s): 8149373

Creating app.py file

Browse files
Files changed (1) hide show
  1. app.py +58 -0
app.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ from transformers import AutoModelForSequenceClassification, AutoTokenizer
4
+
5
+ # Defining the model path relative to the repository root.
6
+ #model_path = "abdullah123456/NLP_Project"
7
+ #model_path = "nlptown/bert-base-multilingual-uncased-sentiment"
8
+ model_path = "abdullah123456/NLP_Project_SA"
9
+
10
+ # Loading the model and tokenizer from the local directory.
11
+ model = AutoModelForSequenceClassification.from_pretrained(model_path)
12
+ tokenizer = AutoTokenizer.from_pretrained(model_path)
13
+
14
+
15
+ # Defining a simple text cleaning function
16
+ def clean_text(text):
17
+ return " ".join(text.split())
18
+
19
+
20
+ # Defining the prediction function that the web interface will use.
21
+ def predict_sentiment(tweet: str) -> str:
22
+
23
+ # Cleaning the tweet
24
+ tweet_clean = clean_text(tweet)
25
+
26
+ # Tokenizing the tweet.
27
+ inputs = tokenizer(tweet_clean, return_tensors="pt", truncation=True, padding="max_length", max_length=128)
28
+
29
+ # Moving the input tensors to the same device as the model.
30
+ inputs = {k: v.to(model.device) for k, v in inputs.items()}
31
+
32
+ with torch.no_grad():
33
+ outputs = model(**inputs)
34
+ # Getting the predicted class index.
35
+ predicted_class = torch.argmax(outputs.logits, dim=1).item()
36
+
37
+ # Defining label mapping.
38
+ label_mapping = {0: "negative", 1: "neutral", 2: "positive"}
39
+ return label_mapping.get(predicted_class, "unknown")
40
+
41
+ # Creating the Gradio Interface.
42
+ iface = gr.Interface(
43
+ fn=predict_sentiment,
44
+ inputs=gr.Textbox(lines=4, placeholder="Enter an Urdu tweet here...", label="Urdu Tweet"),
45
+ outputs=gr.Textbox(label="Predicted Sentiment"),
46
+ title="Urdu Tweet Sentiment Analysis",
47
+ description="This app uses a fine-tuned transformer model to predict the sentiment of Urdu tweets. "
48
+ "Enter your tweet in the textbox below and click 'Submit' to see the prediction.",
49
+ examples=[
50
+ ["السلام علیکم! آج کا دن بہت خوبصورت ہے۔"],
51
+ ["میں بہت غمگین ہوں، دل بہت دکھ رہا ہے۔"],
52
+ ["آپ کا کام بہت اچھا ہے!"]
53
+ ]
54
+ )
55
+
56
+ # Launching the interface.
57
+ if __name__ == "__main__":
58
+ iface.launch()