1from transformers import pipeline
2
3# Load model
4classifier = pipeline("sentiment-analysis",
5 model="tahamued23/roman-urdu-sentiment-analysis")
6
7# Predict
8result = classifier("bahut acha service hai")[0]
9sentiment = result['label'].replace('LABEL_', '')
10sentiment_map = {'2': 'Positive', '1': 'Neutral', '0': 'Negative'}
11
12print(f"Sentiment: {sentiment_map[sentiment]}")
13print(f"Confidence: {result['score']:.2%}")
14# Output: Sentiment: Positive, Confidence: 98.53%
1from transformers import AutoTokenizer, AutoModelForSequenceClassification
2import torch
3
4# Load model and tokenizer
5model_name = "tahamued23/roman-urdu-sentiment-analysis"
6tokenizer = AutoTokenizer.from_pretrained(model_name)
7model = AutoModelForSequenceClassification.from_pretrained(model_name)
8
9# Prepare text
10text = "bilkul bekar experience tha mera"
11inputs = tokenizer(text, return_tensors="pt", padding=True,
12 truncation=True, max_length=128)
13
14# Inference
15model.eval()
16with torch.no_grad():
17 outputs = model(**inputs)
18 probabilities = torch.nn.functional.softmax(outputs.logits, dim=-1)
19 predicted_class = torch.argmax(probabilities, dim=1).item()
20 confidence = probabilities[0][predicted_class].item()
21
22# Label mapping
23sentiment_map = {0: "Negative", 1: "Neutral", 2: "Positive"}
24
25print(f"Text: {text}")
26print(f"Sentiment: {sentiment_map[predicted_class]}")
27print(f"Confidence: {confidence:.2%}")
1# Batch inference for multiple texts
2texts = [
3 "bahut acha service hai",
4 "bilkul bekar experience tha",
5 "theek hai kuch khas nahi tha",
6 "bohat khush hoon main is se",
7 "ye facility bohot kharab hai"
8]
9
10# Process batch
11results = classifier(texts, batch_size=32)
12
13# Display results
14sentiment_map = {'LABEL_2': 'Positive', 'LABEL_1': 'Neutral', 'LABEL_0': 'Negative'}
15for text, result in zip(texts, results):
16 sentiment = sentiment_map[result['label']]
17 confidence = result['score']
18 print(f"📝 {text:<35} → {sentiment:<8} ({confidence:.2%})")
1import asyncio
2from transformers import pipeline
3
4class RomanUrduSentimentAnalyzer:
5 def __init__(self):
6 self.classifier = pipeline(
7 "sentiment-analysis",
8 model="tahamued23/roman-urdu-sentiment-analysis",
9 device=0 # GPU
10 )
11 self.sentiment_map = {'LABEL_2': 'Positive', 'LABEL_1': 'Neutral', 'LABEL_0': 'Negative'}
12
13 async def predict_async(self, text):
14 """Async sentiment prediction"""
15 loop = asyncio.get_event_loop()
16 result = await loop.run_in_executor(
17 None,
18 self.classifier,
19 text
20 )
21 return {
22 'text': text,
23 'sentiment': self.sentiment_map[result[0]['label']],
24 'confidence': result[0]['score']
25 }
26
27 async def batch_predict_async(self, texts):
28 """Async batch prediction"""
29 tasks = [self.predict_async(text) for text in texts]
30 return await asyncio.gather(*tasks)
31
32# Usage
33async def main():
34 analyzer = RomanUrduSentimentAnalyzer()
35 texts = ["bahut acha hai", "bekar hai", "theek hai"]
36 results = await analyzer.batch_predict_async(texts)
37 for result in results:
38 print(f"{result['text']}: {result['sentiment']} ({result['confidence']:.2%})")
39
40# asyncio.run(main())
The model uses a rigorous multi-stage filtering pipeline to identify authentic Roman Urdu text:
1ROMAN_URDU_PATTERNS = [
2 # Pronouns & Basic Verbs
3 r'\b(main|mein|hun|tun|aap|yeh|ye|wo|is|us)\b',
4 r'\b(ha|he|hain|hen|hun|ho|hota|hoti|tha|the|thi|thin)\b',
5
6 # Postpositions (Case markers)
7 r'\b(ka|ke|ki|ko|se|me|par|pe|tak|say)\b',
8
9 # Conjunctions & Question Words
10 r'\b(aur|ya|lekin|magar|kyun|kaise|kahan|kab|kya|jab|tab)\b',
11
12 # Adjectives & Intensifiers
13 r'\b(bahut|bohat|zyada|kafi|thora|bohot|acha|aacha|bura|bekar|theek|thik|kharab)\b',
14
15 # Action Verbs
16 r'\b(kar|kr|karo|karna|karein|karta|karti|kiya|kya|kro)\b',
17
18 # Common Nouns
19 r'\b(ghar|school|university|college|shop|market|hospital|office)\b',
20 r'\b(dost|yar|log|logon|bacche|bachon|admi|aurat)\b',
21
22 # Time & Frequency
23 r'\b(aaj|kal|parson|ab|tab|kabhi|aksar|hamesha)\b',
24
25 # Negations
26 r'\b(nahi|na|mat|bila)\b'
27]
1import requests
2
3API_URL = "https://api-inference.huggingface.co/models/tahamued23/roman-urdu-sentiment-analysis"
4headers = {"Authorization": "Bearer YOUR_HF_TOKEN"}
5
6def query(payload):
7 response = requests.post(API_URL, headers=headers, json=payload)
8 return response.json()
9
10output = query({"inputs": "bahut acha service hai"})
1FROM python:3.9-slim
2
3WORKDIR /app
4COPY requirements.txt .
5RUN pip install -r requirements.txt
6COPY app.py .
7
8CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000"]
1import sagemaker
2from sagemaker.huggingface import HuggingFaceModel
3
4# Create Hugging Face Model Class
5huggingface_model = HuggingFaceModel(
6 model_id="tahamued23/roman-urdu-sentiment-analysis",
7 role=role,
8 transformers_version="4.26",
9 pytorch_version="1.13",
10 py_version="py39",
11)
12
13# Deploy model
14predictor = huggingface_model.deploy(
15 initial_instance_count=1,
16 instance_type="ml.g4dn.xlarge"
17)
1@misc{roman_urdu_sentiment_2026,
2 author = {Taha Mueed},
3 title = {Roman Urdu Sentiment Analysis: A Fine-tuned RoBERTa Model for Urdu in Latin Script},
4 year = {2026},
5 publisher = {Hugging Face Hub},
6 journal = {Hugging Face Model Hub},
7 howpublished = {\url{https://huggingface.co/tahamued23/roman-urdu-sentiment-analysis}},
8 note = {Version 1.0, Accuracy: 88.44\%}
9}
1MIT License
2
3Copyright (c) 2026 Taha Mueed
4
5Permission is hereby granted, free of charge, to any person obtaining a copy
6of this software and associated documentation files (the "Software"), to deal
7in the Software without restriction, including without limitation the rights
8to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9copies of the Software, and to permit persons to whom the Software is
10furnished to do so, subject to the following conditions:
11
12The above copyright notice and this permission notice shall be included in all
13copies or substantial portions of the Software.
14
15THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21SOFTWARE.