Spaces:
Running
Running
Download app.py from yasir776/Sentiment-analysis: direct link, hf CLI and curl.
- Browser
- Download file 16.9 kB
-
https://huggingface.co/spaces/yasir776/Sentiment-analysis/resolve/main/app.py
- Command line
-
hf download hf://spaces/yasir776/Sentiment-analysis/app.py
-
curl -L -o app.py https://huggingface.co/spaces/yasir776/Sentiment-analysis/resolve/main/app.py
16.9 kB
| """ | |
| Smart Text Analyzer | |
| ------------------- | |
| News ya article paste karo, aur ye batayega: | |
| 1. Summary | |
| 2. Category | |
| 3. Sentiment | |
| 4. Keywords | |
| 5. Naam (people / places / organizations) | |
| Output English mein bhi aa sakta hai aur Roman Urdu mein bhi. | |
| """ | |
| import json | |
| import os | |
| import re | |
| import sys | |
| from collections import Counter | |
| import gradio as gr | |
| import torch | |
| from sklearn.feature_extraction.text import ENGLISH_STOP_WORDS | |
| from transformers import AutoModelForSeq2SeqLM, AutoTokenizer, pipeline | |
| # ---------------------------------------------------------------------- | |
| # Settings | |
| # ---------------------------------------------------------------------- | |
| CATEGORIES = ["Sports", "Politics", "Business", "Technology", | |
| "Entertainment", "Health", "Science", "World"] | |
| # category / sentiment ke Roman Urdu naam (inke liye model ki zaroorat nahi) | |
| CATEGORY_UR = { | |
| "Sports": "Khel", "Politics": "Siyasat", "Business": "Karobar", | |
| "Technology": "Technology", "Entertainment": "Tafreeh", | |
| "Health": "Sehat", "Science": "Science", "World": "Duniya", | |
| } | |
| SENTIMENT_UR = {"Positive": "Musbat", "Negative": "Manfi", "Neutral": "Ghair Janibdar"} | |
| ENTITY_UR = {"People": "Log", "Places": "Jagahain", "Organizations": "Idaray", "Other": "Dusray"} | |
| # ---------------------------------------------------------------------- | |
| # Models load karna (pehli baar thora time lagega, download hota hai) | |
| # Chhote (distil) models liye hain taake Colab / free hosting par chal saken | |
| # ---------------------------------------------------------------------- | |
| print("Models load ho rahe hain, thora intezar karein...") | |
| device = "cuda" if torch.cuda.is_available() else "cpu" | |
| pipe_device = 0 if torch.cuda.is_available() else -1 # pipelines ke liye (0 = GPU) | |
| # Summary aur translation ke liye hum pipeline() nahi, seedha model use karte hain. | |
| # Wajah: transformers ke naye version (v5) mein "summarization" aur "translation" | |
| # pipelines hata di gayi hain. Ye tareeqa har version mein chalta hai. | |
| def load_seq2seq(model_name, **tokenizer_kwargs): | |
| tokenizer = AutoTokenizer.from_pretrained(model_name, **tokenizer_kwargs) | |
| model = AutoModelForSeq2SeqLM.from_pretrained(model_name).to(device) | |
| model.eval() | |
| return tokenizer, model | |
| def run_seq2seq(tokenizer, model, text, max_length, min_length=0, **gen_kwargs): | |
| inputs = tokenizer(text, return_tensors="pt", truncation=True).to(device) | |
| with torch.no_grad(): | |
| output_ids = model.generate( | |
| **inputs, max_length=max_length, min_length=min_length, | |
| num_beams=4, early_stopping=True, **gen_kwargs, | |
| ) | |
| return tokenizer.decode(output_ids[0], skip_special_tokens=True) | |
| sum_tokenizer, sum_model = load_seq2seq("sshleifer/distilbart-cnn-12-6") | |
| # baaqi teen kaam ke pipelines abhi bhi har version mein maujood hain | |
| classifier = pipeline("zero-shot-classification", model="valhalla/distilbart-mnli-12-3", | |
| device=pipe_device) | |
| sentiment_model = pipeline( | |
| "sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english", | |
| device=pipe_device, | |
| ) | |
| ner_model = pipeline("ner", model="dslim/bert-base-NER", aggregation_strategy="simple", | |
| device=pipe_device) | |
| # translation model sirf tab load hoga jab Roman Urdu mangein | |
| _translator = None | |
| def get_translator(): | |
| global _translator | |
| if _translator is None: | |
| print("Translation model load ho raha hai...") | |
| _translator = load_seq2seq("facebook/nllb-200-distilled-600M", src_lang="eng_Latn") | |
| return _translator | |
| # ---------------------------------------------------------------------- | |
| # Chhoti chhoti helper functions | |
| # ---------------------------------------------------------------------- | |
| def split_into_chunks(text, max_words=600): | |
| """Lamba text models ki limit se bara hota hai, isliye tukron mein baant lete hain.""" | |
| words = text.split() | |
| return [" ".join(words[i:i + max_words]) for i in range(0, len(words), max_words)] | |
| def split_sentences(text): | |
| parts = re.split(r"(?<=[.!?])\s+", text.strip()) | |
| return [p for p in parts if p] | |
| def make_summary(text): | |
| word_count = len(text.split()) | |
| if word_count < 40: | |
| return text # itna chhota text hai, summary ki zaroorat nahi | |
| chunks = split_into_chunks(text, 600) | |
| # aakhri tukra bohat chhota ho to pichle ke saath jor do, warna model bakwas likhta hai | |
| if len(chunks) > 1 and len(chunks[-1].split()) < 50: | |
| last_chunk = chunks.pop() | |
| chunks[-1] += " " + last_chunk | |
| pieces = [] | |
| for chunk in chunks: | |
| n = len(chunk.split()) | |
| max_len = min(130, max(25, int(n * 0.6))) | |
| min_len = min(30, max_len - 5) | |
| pieces.append(run_seq2seq(sum_tokenizer, sum_model, chunk, max_len, min_len)) | |
| joined = " ".join(pieces) | |
| # agar bohat lamba article tha to summary ki bhi summary bana lo | |
| if len(pieces) > 1 and len(joined.split()) > 150: | |
| joined = run_seq2seq(sum_tokenizer, sum_model, joined, 130, 40) | |
| return joined | |
| def find_category(text): | |
| result = classifier(text[:2000], CATEGORIES) | |
| top_label = result["labels"][0] | |
| top_score = result["scores"][0] | |
| return top_label, top_score | |
| def find_sentiment(text): | |
| result = sentiment_model(text[:2000], truncation=True, max_length=512)[0] | |
| label = result["label"].capitalize() | |
| score = result["score"] | |
| # agar model ko khud pakka yaqeen nahi to neutral maan lo | |
| if score < 0.65: | |
| label = "Neutral" | |
| return label, score | |
| def find_keywords(text, top_n=8): | |
| words = re.findall(r"[a-zA-Z]{4,}", text.lower()) | |
| words = [w for w in words if w not in ENGLISH_STOP_WORDS] | |
| return [w for w, _ in Counter(words).most_common(top_n)] | |
| def find_entities(text): | |
| groups = {"People": set(), "Places": set(), "Organizations": set(), "Other": set()} | |
| mapping = {"PER": "People", "LOC": "Places", "ORG": "Organizations", "MISC": "Other"} | |
| for chunk in split_into_chunks(text, 200): | |
| for ent in ner_model(chunk): | |
| name = ent["word"].strip() | |
| if len(name) < 2 or name.startswith("##"): | |
| continue | |
| groups[mapping.get(ent["entity_group"], "Other")].add(name) | |
| return {k: sorted(v) for k, v in groups.items() if v} | |
| def basic_stats(text): | |
| words = len(text.split()) | |
| sentences = len(split_sentences(text)) | |
| minutes = max(1, round(words / 200)) | |
| return words, sentences, minutes | |
| # ---------------------------------------------------------------------- | |
| # Roman Urdu wala hissa | |
| # Plan: English -> Urdu (translation model) -> Roman Urdu (transliteration) | |
| # Agar ANTHROPIC_API_KEY set ho to Claude se behtar Roman Urdu le lete hain. | |
| # ---------------------------------------------------------------------- | |
| URDU_LETTERS = { | |
| "ا": "a", "آ": "aa", "ب": "b", "پ": "p", "ت": "t", "ٹ": "t", "ث": "s", | |
| "ج": "j", "چ": "ch", "ح": "h", "خ": "kh", "د": "d", "ڈ": "d", "ذ": "z", | |
| "ر": "r", "ڑ": "r", "ز": "z", "ژ": "zh", "س": "s", "ش": "sh", "ص": "s", | |
| "ض": "z", "ط": "t", "ظ": "z", "ع": "a", "غ": "gh", "ف": "f", "ق": "q", | |
| "ک": "k", "گ": "g", "ل": "l", "م": "m", "ن": "n", "ں": "n", "و": "o", | |
| "ہ": "h", "ھ": "h", "ء": "", "ی": "i", "ے": "e", "ئ": "i", "ۃ": "h", | |
| "ً": "", "ُ": "", "ِ": "", "َ": "", "ّ": "", "ٰ": "", | |
| "۔": ".", "،": ",", "؟": "?", "؛": ";", | |
| "۰": "0", "۱": "1", "۲": "2", "۳": "3", "۴": "4", | |
| "۵": "5", "۶": "6", "۷": "7", "۸": "8", "۹": "9", | |
| } | |
| # Aam lafzon ki spelling theek rakhne ke liye chhoti si dictionary. | |
| # Baaqi lafz letter-by-letter convert hote hain. | |
| COMMON_WORDS = { | |
| "ہے": "hai", "ہیں": "hain", "تھا": "tha", "تھی": "thi", "تھے": "thay", | |
| "کی": "ki", "کا": "ka", "کے": "ke", "کو": "ko", "نے": "ne", "سے": "se", | |
| "میں": "mein", "پر": "par", "اور": "aur", "یہ": "yeh", "وہ": "woh", | |
| "اس": "is", "ان": "un", "جو": "jo", "کہ": "ke", "بھی": "bhi", "ایک": "aik", | |
| "کر": "kar", "ہو": "ho", "ہوا": "hua", "ہوئی": "hui", "ہوں": "hon", | |
| "کیا": "kiya", "گیا": "gaya", "گئی": "gayi", "گئے": "gaye", "لیے": "liye", | |
| "ساتھ": "saath", "نہیں": "nahi", "تک": "tak", "بعد": "baad", "لیکن": "lekin", | |
| "سال": "saal", "حکومت": "hukumat", "پاکستان": "Pakistan", "کرنے": "karne", | |
| "کرتے": "karte", "کرتا": "karta", "والے": "walay", "والی": "wali", | |
| "والا": "wala", "گا": "ga", "گی": "gi", "گے": "ge", "دیا": "diya", | |
| "لیا": "liya", "اپنے": "apne", "اپنی": "apni", "اپنا": "apna", "کچھ": "kuch", | |
| "سب": "sab", "بہت": "bohat", "ملک": "mulk", "لوگ": "log", "دن": "din", | |
| "پہلے": "pehle", "اب": "ab", "جب": "jab", "تو": "to", "بھی": "bhi", | |
| "کہا": "kaha", "کہنا": "kehna", "ہم": "hum", "آپ": "aap", "میں": "mein", | |
| } | |
| PUNCTUATION = "۔،؟؛.,!?;:\"'()[]" | |
| def urdu_to_roman(urdu_text): | |
| out_words = [] | |
| for token in urdu_text.split(): | |
| core = token.strip(PUNCTUATION) | |
| # sirf punctuation wala token (jaise "۔") seedha convert kar do | |
| if not core: | |
| out_words.append("".join(URDU_LETTERS.get(ch, ch) for ch in token)) | |
| continue | |
| # lafz ke aage peeche ki punctuation alag rakho taake dictionary mein lafz mil sake | |
| prefix = token[:len(token) - len(token.lstrip(PUNCTUATION))] | |
| suffix = token[len(token.rstrip(PUNCTUATION)):] | |
| if core in COMMON_WORDS: | |
| roman = COMMON_WORDS[core] | |
| else: | |
| roman = "".join(URDU_LETTERS.get(ch, ch) for ch in core) | |
| prefix = "".join(URDU_LETTERS.get(ch, ch) for ch in prefix) | |
| suffix = "".join(URDU_LETTERS.get(ch, ch) for ch in suffix) | |
| out_words.append(prefix + roman + suffix) | |
| return " ".join(out_words) | |
| def get_api_key(): | |
| """Key pehle environment se dhoondte hain, phir Colab Secrets se.""" | |
| key = os.environ.get("ANTHROPIC_API_KEY") | |
| if key: | |
| return key | |
| try: | |
| from google.colab import userdata | |
| return userdata.get("ANTHROPIC_API_KEY") | |
| except Exception: | |
| return None | |
| def roman_urdu_with_claude(summary, keywords): | |
| """Claude se natural Roman Urdu. Kamyab ho to ((summary, keywords), None) deta hai.""" | |
| api_key = get_api_key() | |
| if not api_key: | |
| return None, "API key nahi mili" | |
| try: | |
| import anthropic | |
| client = anthropic.Anthropic(api_key=api_key) | |
| prompt = ( | |
| "Neeche di gayi English summary aur keywords ko natural Roman Urdu mein likho " | |
| "(Urdu zubaan, English huroof mein), jaise Pakistani log WhatsApp par likhte hain. " | |
| "Aam Urdu lafz use karo (hukumat, khabar, jeet), Hindi/Sanskrit wale nahi. " | |
| "Naam (log, shehar, idaray) jaisay hain waisay hi rakho.\n\n" | |
| "Jawab sirf is JSON format mein do, aur kuch nahi:\n" | |
| '{"summary": "...", "keywords": ["...", "..."]}\n\n' | |
| f"Summary: {summary}\n\nKeywords: {', '.join(keywords)}" | |
| ) | |
| reply = client.messages.create( | |
| model="claude-sonnet-5-5", | |
| max_tokens=1500, | |
| messages=[{"role": "user", "content": prompt}], | |
| ) | |
| raw = reply.content[0].text.strip() | |
| raw = re.sub(r"^```(?:json)?\s*|\s*```$", "", raw).strip() | |
| data = json.loads(raw) | |
| return (data["summary"], ", ".join(data["keywords"])), None | |
| except Exception as err: | |
| print("Claude API error:", err) | |
| return None, str(err)[:120] | |
| def local_roman_urdu(text): | |
| """Bina API ke: English -> Urdu (NLLB model) -> Roman Urdu (rules). Kam accurate.""" | |
| tr_tokenizer, tr_model = get_translator() | |
| urdu_id = tr_tokenizer.convert_tokens_to_ids("urd_Arab") | |
| urdu_sentences = [ | |
| run_seq2seq(tr_tokenizer, tr_model, sent, 256, forced_bos_token_id=urdu_id) | |
| for sent in split_sentences(text) | |
| ] | |
| return urdu_to_roman(" ".join(urdu_sentences)) | |
| def to_roman_urdu(summary, keywords): | |
| """(summary, keywords, note) return karta hai. note mein batata hai ke kya hua.""" | |
| result, problem = roman_urdu_with_claude(summary, keywords) | |
| if result: | |
| return result[0], result[1], "" | |
| note = (f"Note: Claude se Roman Urdu nahi ban saki ({problem}), is liye local model " | |
| "use hua jo kam accurate hai. Behtar nateeje ke liye ANTHROPIC_API_KEY lagayein.") | |
| try: | |
| return local_roman_urdu(summary), ", ".join(keywords), note | |
| except Exception as err: | |
| print("Local translation error:", err) | |
| return summary, ", ".join(keywords), note + " Local translation bhi nahi chali, English dikhayi gayi." | |
| # ---------------------------------------------------------------------- | |
| # Main function jo button dabane par chalta hai | |
| # ---------------------------------------------------------------------- | |
| def analyze(text, language): | |
| text = (text or "").strip() | |
| if len(text.split()) < 15: | |
| return "Pehle kam az kam 15-20 lafzon ka text paste karein.", "", "" | |
| summary = make_summary(text) | |
| category, cat_score = find_category(text) | |
| sentiment, sent_score = find_sentiment(text) | |
| keywords = find_keywords(text) | |
| entities = find_entities(text) | |
| words, sentences, minutes = basic_stats(text) | |
| note = "" | |
| if language == "Roman Urdu": | |
| summary_out, keywords_ur, note = to_roman_urdu(summary, keywords) | |
| category_out = f"{CATEGORY_UR.get(category, category)} ({cat_score * 100:.0f}% yaqeen)" | |
| sentiment_out = f"{SENTIMENT_UR.get(sentiment, sentiment)} ({sent_score * 100:.0f}%)" | |
| keywords_out = keywords_ur if keywords else "Koi nahi" | |
| lines = [] | |
| for group, names in entities.items(): | |
| lines.append(f"**{ENTITY_UR[group]}:** " + ", ".join(names)) | |
| entities_out = "\n\n".join(lines) or "Koi naam nahi mila." | |
| stats_out = (f"Lafz: {words} | Jumlay: {sentences} | " | |
| f"Parhne ka waqt: takreeban {minutes} minute") | |
| else: | |
| summary_out = summary | |
| category_out = f"{category} ({cat_score * 100:.0f}% confidence)" | |
| sentiment_out = f"{sentiment} ({sent_score * 100:.0f}%)" | |
| keywords_out = ", ".join(keywords) if keywords else "None" | |
| lines = [f"**{group}:** " + ", ".join(names) for group, names in entities.items()] | |
| entities_out = "\n\n".join(lines) or "No named entities found." | |
| stats_out = (f"Words: {words} | Sentences: {sentences} | " | |
| f"Reading time: about {minutes} min") | |
| details = (f"**Sentiment:** {sentiment_out}\n\n" | |
| f"**Keywords:** {keywords_out}\n\n" | |
| f"{entities_out}\n\n" | |
| f"_{stats_out}_") | |
| if note: | |
| details += f"\n\n{note}" | |
| return summary_out, category_out, details | |
| # ---------------------------------------------------------------------- | |
| # Web interface (Gradio) | |
| # ---------------------------------------------------------------------- | |
| SAMPLE = ( | |
| "Pakistan's cricket team secured a thrilling victory against Australia in Karachi on " | |
| "Sunday, chasing down a target of 280 runs with two wickets in hand. Captain Babar Azam " | |
| "scored a brilliant century and was named player of the match. The Pakistan Cricket Board " | |
| "praised the team's performance, and thousands of fans celebrated outside the National " | |
| "Stadium. The series now stands level at one match each, with the decider scheduled to be " | |
| "played in Lahore next week." | |
| ) | |
| with gr.Blocks(title="Smart Text Analyzer") as demo: | |
| gr.Markdown("# Smart Text Analyzer\nNews ya article paste karein aur summary, category " | |
| "aur analysis hasil karein.") | |
| with gr.Row(): | |
| with gr.Column(scale=3): | |
| text_in = gr.Textbox(label="Article / News yahan paste karein", lines=14, | |
| placeholder="Yahan text paste karein...") | |
| language = gr.Radio(["English", "Roman Urdu"], value="English", | |
| label="Output ki zubaan") | |
| with gr.Row(): | |
| run_btn = gr.Button("Analyze Karein", variant="primary") | |
| sample_btn = gr.Button("Sample Text") | |
| with gr.Column(scale=3): | |
| summary_out = gr.Textbox(label="Summary", lines=6) | |
| category_out = gr.Textbox(label="Category") | |
| details_out = gr.Markdown() | |
| run_btn.click(analyze, inputs=[text_in, language], | |
| outputs=[summary_out, category_out, details_out]) | |
| sample_btn.click(lambda: SAMPLE, outputs=text_in) | |
| if __name__ == "__main__": | |
| in_colab = "google.colab" in sys.modules or "COLAB_GPU" in os.environ | |
| # Colab mein share=True se public link milta hai | |
| # (Hugging Face Spaces par apni link hoti hai, wahan share ki zaroorat nahi) | |
| on_hf_space = "SPACE_ID" in os.environ | |
| demo.launch(share=(in_colab or not on_hf_space)) | |