CoolFace
Apppublic

dnzblgn/Sarcasm_Detection

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
app.py168 linesDownload Raw Back to root
1import gradio as gr2import torch3import torch.nn.functional as F4from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline, DistilBertTokenizer, DistilBertForSequenceClassification5 6# ---------------- Original Sarcasm + Sentiment Models ----------------7sarcasm_model = AutoModelForSequenceClassification.from_pretrained("dnzblgn/Sarcasm-Detection-Customer-Reviews")8sarcasm_tokenizer = AutoTokenizer.from_pretrained("dnzblgn/Sarcasm-Detection-Customer-Reviews", use_fast=False)9 10sentiment_model = AutoModelForSequenceClassification.from_pretrained("dnzblgn/Sentiment-Analysis-Customer-Reviews")11sentiment_tokenizer = AutoTokenizer.from_pretrained("dnzblgn/Sentiment-Analysis-Customer-Reviews", use_fast=False)12 13def analyze_sentiment(sentence):14    inputs = sentiment_tokenizer(sentence, return_tensors="pt", truncation=True, padding=True, max_length=512)15    with torch.no_grad():16        outputs = sentiment_model(**inputs)17    logits = outputs.logits18    predicted_class = torch.argmax(logits, dim=-1).item()19    sentiment_mapping = {1: "Negative", 0: "Positive"}20    return sentiment_mapping[predicted_class]21 22def detect_sarcasm(sentence):23    inputs = sarcasm_tokenizer(sentence, return_tensors="pt", truncation=True, padding=True, max_length=512)24    with torch.no_grad():25        outputs = sarcasm_model(**inputs)26    logits = outputs.logits27    predicted_class = torch.argmax(logits, dim=-1).item()28    return "Sarcasm" if predicted_class == 1 else "Not Sarcasm"29 30def process_text_pipeline(text):31    sentences = text.split("\n")32    processed_sentences = []33 34    for sentence in sentences:35        sentence = sentence.strip()36        if not sentence:37            continue38 39        sentiment = analyze_sentiment(sentence)40        if sentiment == "Negative":41            processed_sentences.append(f"❌ '{sentence}' -> Sentiment: Negative")42        else:43            sarcasm_result = detect_sarcasm(sentence)44            if sarcasm_result == "Sarcasm":45                processed_sentences.append(f"⚠️ '{sentence}' -> Sentiment: Negative (Sarcastic Positive)")46            else:47                processed_sentences.append(f"✅ '{sentence}' -> Sentiment: Positive")48 49    return "\n".join(processed_sentences)50 51# ---------------- Additional Sentiment Models (No Sarcasm) ----------------52# Pre-load tokenizers + models for safety53additional_models = {54    "siebert/sentiment-roberta-large-english": {55        "tokenizer": AutoTokenizer.from_pretrained("siebert/sentiment-roberta-large-english"),56        "model": AutoModelForSequenceClassification.from_pretrained("siebert/sentiment-roberta-large-english")57    },58    "assemblyai/bert-large-uncased-sst2": {59        "tokenizer": AutoTokenizer.from_pretrained("assemblyai/bert-large-uncased-sst2"),60        "model": AutoModelForSequenceClassification.from_pretrained("assemblyai/bert-large-uncased-sst2")61    },62    "j-hartmann/sentiment-roberta-large-english-3-classes": {63        "tokenizer": AutoTokenizer.from_pretrained("j-hartmann/sentiment-roberta-large-english-3-classes"),64        "model": AutoModelForSequenceClassification.from_pretrained("j-hartmann/sentiment-roberta-large-english-3-classes")65    },66    "cardiffnlp/twitter-xlm-roberta-base-sentiment": {67        "tokenizer": AutoTokenizer.from_pretrained("cardiffnlp/twitter-xlm-roberta-base-sentiment"),68        "model": AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-xlm-roberta-base-sentiment")69    },70    "sohan-ai/sentiment-analysis-model-amazon-reviews": {71        "tokenizer": DistilBertTokenizer.from_pretrained("distilbert-base-uncased"),72        "model": DistilBertForSequenceClassification.from_pretrained("sohan-ai/sentiment-analysis-model-amazon-reviews")73    }74}75 76def run_sentiment_with_selected_model(text, model_name):77    model_info = additional_models[model_name]78    tokenizer = model_info["tokenizer"]79    model = model_info["model"]80 81    inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True)82    with torch.no_grad():83        outputs = model(**inputs)84 85    logits = outputs.logits86    probs = F.softmax(logits, dim=-1)87    pred = torch.argmax(probs, dim=-1).item()88 89    # Custom label mapping90    label_map = {91        "assemblyai/bert-large-uncased-sst2": {0: "Negative", 1: "Positive"},92        "sohan-ai/sentiment-analysis-model-amazon-reviews": {0: "Negative", 1: "Positive"},93    }94 95    if model_name in label_map:96        label = label_map[model_name][pred]97    elif model.config.id2label:98        label = model.config.id2label.get(pred, f"LABEL_{pred}")99    else:100        label = f"LABEL_{pred}"101 102    emoji = "✅" if "positive" in label.lower() else "❌" if "negative" in label.lower() else "⚠️"103    104    # Add confidence score105    confidence = probs[0][pred].item() * 100106    return f"{emoji} '{text}' -> {label} ({confidence:.1f}%)"107 108# ---------------- Gradio UI ----------------109background_css = """110.gradio-container {111    background-image: url('https://huggingface.co/spaces/dnzblgn/Sarcasm_Detection/resolve/main/image.png');112    background-size: cover;113    background-position: center;114    color: white;115}116.gr-input, .gr-textbox {117    background-color: rgba(255, 255, 255, 0.3) !important;118    border-radius: 10px;119    padding: 10px;120    color: black !important;121}122h1, h2, p {123    text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.8);124}125"""126 127with gr.Blocks(css=background_css) as interface:128    gr.Markdown(129        """130        <h1 style='text-align: center; font-size: 36px;'>🌟 Sentiment Analysis Powered by Sarcasm Detection 🌟</h1>131        <p style='text-align: center; font-size: 18px;'>Analyze the sentiment of customer reviews and detect sarcasm in positive reviews.</p>132        """133    )134 135    with gr.Tab("Text Input"):136        with gr.Row():137            text_input = gr.Textbox(lines=10, label="Enter Sentences", placeholder="Enter one or more sentences, each on a new line.")138            result_output = gr.Textbox(label="Results", lines=10, interactive=False)139        analyze_button = gr.Button("🔍 Analyze")140        analyze_button.click(process_text_pipeline, inputs=text_input, outputs=result_output)141 142    with gr.Tab("Upload Text File"):143        file_input = gr.File(label="Upload Text File")144        file_output = gr.Textbox(label="Results", lines=10, interactive=False)145 146        def process_file(file):147            text = file.read().decode("utf-8")148            return process_text_pipeline(text)149 150        file_input.change(process_file, inputs=file_input, outputs=file_output)151 152    with gr.Tab("Try Other Sentiment Models"):153        with gr.Row():154            other_model_selector = gr.Dropdown(155                choices=list(additional_models.keys()),156                label="Choose a Sentiment Model"157            )158        with gr.Row():159            model_text_input = gr.Textbox(lines=5, label="Enter Sentence")160            model_result_output = gr.Textbox(label="Sentiment", lines=3, interactive=False)161 162        run_model_btn = gr.Button("Run")163        run_model_btn.click(run_sentiment_with_selected_model, inputs=[model_text_input, other_model_selector], outputs=model_result_output)164 165# ---------------- Run App ----------------166if __name__ == "__main__":167    interface.launch()168