CoolFace
Apppublic

eventdata-utd/ConfliBERT-MME

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
app.py172 linesDownload Raw Back to root
1import torch2import tensorflow as tf3from tf_keras import models, layers4from transformers import AutoTokenizer, AutoModelForSequenceClassification, AutoModelForTokenClassification, TFAutoModelForQuestionAnswering5import gradio as gr6import re7 8# Check if GPU is available and use it if possible9device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')10 11# Load the model and tokenizer12mme_model_name = 'sperkins2116/ConfliBERT-BC-MMEs'13mme_model = AutoModelForSequenceClassification.from_pretrained(mme_model_name).to(device)14mme_tokenizer = AutoTokenizer.from_pretrained(mme_model_name)15 16# Define the class names for text classification17class_names = ['Negative', 'Positive']18 19def handle_error_message(e, default_limit=512):20    error_message = str(e)21    pattern = re.compile(r"The size of tensor a \((\d+)\) must match the size of tensor b \((\d+)\)")22    match = pattern.search(error_message)23    if match:24        number_1, number_2 = match.groups()25        return f"<span style='color: red; font-weight: bold;'>Error: Text Input is over limit where inserted text size {number_1} is larger than model limits of {number_2}</span>"26    return f"<span style='color: red; font-weight: bold;'>Error: Text Input is over limit where inserted text size is larger than model limits of {default_limit}</span>"27 28def mme_classification(text):29    try:30        inputs = mme_tokenizer(text, return_tensors='pt', truncation=True, padding=True).to(device)31        with torch.no_grad():32            outputs = mme_model(**inputs)33        logits = outputs.logits.squeeze().tolist()34        predicted_class = torch.argmax(outputs.logits, dim=1).item()35        confidence = torch.softmax(outputs.logits, dim=1).max().item() * 10036 37        if predicted_class == 1:  # Positive class38            result = f"<span style='color: green; font-weight: bold;'>Positive: The text contains evidence of a multinational military exercise. (Confidence: {confidence:.2f}%)</span>"39        else:  # Negative class40            result = f"<span style='color: red; font-weight: bold;'>Negative: The text does not contain evidence of a multinational military exercise. (Confidence: {confidence:.2f}%)</span>"41        return result42    except Exception as e:43        return handle_error_message(e)44 45# Define the Gradio interface46def chatbot(text):47    return mme_classification(text)48 49css = """50body {51    background-color: #f0f8ff;52    font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;53    color: black; /* Ensure text is visible in dark mode */54}55 56h1 {57    color: #2e8b57;58    text-align: center;59    font-size: 2em;60}61 62h2 {63    color: #ff8c00;64    text-align: center;65    font-size: 1.5em;66}67 68.gradio-container {69    max-width: 100%;70    margin: 10px auto;71    padding: 10px;72    background-color: #ffffff;73    border-radius: 10px;74    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);75}76 77.gr-input, .gr-output {78    background-color: #ffffff;79    border: 1px solid #ddd;80    border-radius: 5px;81    padding: 10px;82    font-size: 1em;83    color: black; /* Ensure text is visible in dark mode */84}85 86.gr-title {87    font-size: 1.5em;88    font-weight: bold;89    color: #2e8b57;90    margin-bottom: 10px;91    text-align: center;92}93 94.gr-description {95    font-size: 1.2em;96    color: #ff8c00;97    margin-bottom: 10px;98    text-align: center;99}100 101.header {102    display: flex;103    justify-content: center;104    align-items: center;105    padding: 10px;106    flex-wrap: wrap;107}108 109.header-title-center a {110    font-size: 4em;  /* Increased font size */111    font-weight: bold;  /* Made text bold */112    color: darkorange;  /* Darker orange color */113    text-align: center;114    display: block;115}116 117.gr-button {118    background-color: #ff8c00;119    color: white;120    border: none;121    padding: 10px 20px;122    font-size: 1em;123    border-radius: 5px;124    cursor: pointer;125}126 127.gr-button:hover {128    background-color: #ff4500;129}130 131.footer {132    text-align: center;133    margin-top: 10px;134    font-size: 0.9em;  /* Updated font size */135    color: black; /* Ensure text is visible in dark mode */136    width: 100%;137}138 139.footer a {140    color: #2e8b57;141    font-weight: bold;142    text-decoration: none;143}144 145.footer a:hover {146    text-decoration: underline;147}148 149.footer .inline {150    display: inline;151    color: black; /* Ensure text is visible in dark mode */152}153"""154 155with gr.Blocks(css=css) as demo:156    with gr.Row(elem_id="header"):157        gr.Markdown("<div class='header-title-center'><a href='https://eventdata.utdallas.edu/conflibert/'>ConfliBERT-MME</a></div>", elem_id="header-title-center")158    159    gr.Markdown("<span style='color: black;'>Provide the text for MME Classification.</span>")160    161    text_input = gr.Textbox(lines=5, placeholder="Enter the text here...", label="Text")162    163    output = gr.HTML(label="Output")164    165    submit_button = gr.Button("Submit", elem_id="gr-button")166    submit_button.click(fn=chatbot, inputs=text_input, outputs=output)167    168    gr.Markdown("<div class='footer'><a href='https://eventdata.utdallas.edu/'>UTD Event Data</a> | <a href='https://www.utdallas.edu/'>University of Texas at Dallas</a> | <a href='https://www.wvu.edu/'>West Virginia University</a></div>")169    gr.Markdown("<div class='footer'><span class='inline'>Developed By: <a href='https://www.linkedin.com/in/sultan-alsarra-phd-56977a63/' target='_blank'>Sultan Alsarra</a> | Finetuned By: Spencer Perkins</span></div>")170 171demo.launch(share=True)172