roncc13/CMD_BERT_FINAL
0
1import gradio as gr2from transformers import AutoTokenizer, AutoModelForSequenceClassification3import torch4from theme import custom_css, header5 6# --------------------------7# Model setup8# --------------------------9MODEL_ID = "roncc13/autotrain-ixzm9-t6dbc"10 11tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)12model = AutoModelForSequenceClassification.from_pretrained(MODEL_ID)13 14label_names = ["fake", "real"]15 16 17def classify(text: str):18 if not text.strip():19 return {"fake": 0.0, "real": 0.0}20 inputs = tokenizer(21 text,22 return_tensors="pt",23 truncation=True,24 padding=True,25 max_length=256,26 )27 with torch.no_grad():28 outputs = model(**inputs)29 probs = torch.softmax(outputs.logits, dim=-1)[0].tolist()30 return {label_names[i]: float(probs[i]) for i in range(len(label_names))}31 32 33# --------------------------34# UI with Tabs35# --------------------------36with gr.Blocks(fill_height=True) as demo:37 gr.HTML("<div style='height:8px;'></div>")38 39 # ===== Analyzer tab =====40 with gr.Tab("Analyzer"):41 header()42 43 gr.HTML(44 """45 <section style="margin:0 auto 22px auto; max-width:1120px;">46 <div class="hero-title">47 Check Cebuano text for a misleading writing style.48 </div>49 <div class="hero-subtitle">50 This tool analyzes linguistic patterns and writing style in Cebuano text to detect potential51 misinformation. It does not verify factual correctness. The model returns a classification52 (Fake/Legit) and a confidence score based on writing patterns.53 </div>54 </section>55 """56 )57 58 with gr.Row(elem_classes=["two-col"], equal_height=True):59 # Left: input card60 with gr.Column(scale=3):61 with gr.Group(elem_classes=["glass-card"], elem_id="input-card"):62 gr.Markdown(63 "#### Text input\n"64 "Cebuano only. This tool checks linguistic patterns; it does not verify facts."65 )66 gr.Markdown(67 "> **Example** \n"68 "> \u201cNakadisubre og milagro nga tambal sa COVID\u201119 ang usa ka local doktor, "69 "giingon nga walay side effects ug dili kinahanglan og bakuna.\u201d"70 )71 news_text = gr.Textbox(72 lines=7,73 label="",74 placeholder="Paste Cebuano news text here...",75 elem_id="news-textbox",76 )77 with gr.Row():78 analyze_btn = gr.Button("Analyze", elem_classes=["btn-primary-custom"])79 clear_btn = gr.Button("Clear", elem_classes=["btn-secondary-custom"])80 gr.Markdown(81 "<span style='font-size:11px;opacity:0.8;'>"82 "Tip: Keep inputs under 1,000 characters for faster results."83 "</span>",84 container=False,85 )86 87 # Right: result card88 with gr.Column(scale=2):89 with gr.Group(elem_classes=["glass-card"], elem_id="result-card"):90 gr.Markdown("#### Result")91 result_label_html = gr.HTML(92 '<span class="badge-pill badge-fake">FAKE</span>'93 )94 conf_text = gr.HTML(95 """96 <div style="display:flex;align-items:flex-end;gap:6px;margin-top:10px;">97 <span style="font-size:28px;font-weight:600;" id="conf-val">0.00</span>98 <span style="font-size:12px;opacity:0.8;">confidence</span>99 </div>100 """101 )102 conf_bar = gr.HTML(103 """104 <div class="conf-bar-bg">105 <div class="conf-bar-fill" style="width:0%;"></div>106 </div>107 """108 )109 gr.Markdown(110 "<span style='font-size:11px;opacity:0.85;'>"111 "Model: CMD\u2011BERT (fine\u2011tuned BERT\u2011base). "112 "Output: Label and confidence score for the submitted text."113 "</span>",114 container=False,115 )116 117 def analyze_ui(text):118 probs = classify(text)119 fake_p = probs.get("fake", 0.0)120 real_p = probs.get("real", 0.0)121 if fake_p >= real_p:122 label, css_class, conf = "FAKE", "badge-pill badge-fake", fake_p123 else:124 label, css_class, conf = "LEGIT", "badge-pill badge-real", real_p125 conf_pct = int(conf * 100)126 label_html = f'<span class="{css_class}">{label}</span>'127 conf_html = (128 "<div style='display:flex;align-items:flex-end;gap:6px;margin-top:10px;'>"129 f"<span style='font-size:28px;font-weight:600;' id='conf-val'>{conf:.2f}</span>"130 "<span style='font-size:12px;opacity:0.8;'>confidence</span>"131 "</div>"132 )133 bar_html = (134 "<div class='conf-bar-bg'>"135 f"<div class='conf-bar-fill' style='width:{conf_pct}%;'></div>"136 "</div>"137 )138 return label_html, conf_html, bar_html139 140 analyze_btn.click(fn=analyze_ui, inputs=news_text, outputs=[result_label_html, conf_text, conf_bar])141 clear_btn.click(fn=lambda: "", inputs=None, outputs=[news_text])142 143 # ===== How it works tab =====144 with gr.Tab("How it works"):145 header()146 with gr.Group(elem_classes=["glass-card"], elem_id="hiw-intro-card"):147 gr.Markdown(148 "## How CMD\u2011BERT works\n"149 "CMD\u2011BERT is an AI\u2011augmented linguistic model that focuses on writing style, "150 "not literal truth. It looks for patterns such as exaggerated wording, "151 "over\u2011confident claims, and framing that often appear in misleading content."152 )153 with gr.Row():154 with gr.Column():155 with gr.Group(elem_classes=["glass-card"], elem_id="hiw-step1-card"):156 gr.Markdown(157 "### 1. Input and preprocessing\n"158 "- User pastes a Cebuano headline, post, or short article.\n"159 "- The text is tokenized and trimmed to a safe maximum length.\n"160 "- Inputs are processed in memory and not stored permanently."161 )162 with gr.Column():163 with gr.Group(elem_classes=["glass-card"], elem_id="hiw-step2-card"):164 gr.Markdown(165 "### 2. CMD\u2011BERT analysis\n"166 "- CMD\u2011BERT is a fine\u2011tuned BERT\u2011base model trained on Cebuano news.\n"167 "- It computes probabilities for two classes: **Fake** and **Legit**.\n"168 "- The highest\u2011probability class becomes the predicted label."169 )170 with gr.Group(elem_classes=["glass-card"], elem_id="hiw-step3-card"):171 gr.Markdown(172 "### 3. Result and interpretation\n"173 "- The interface shows the predicted label and confidence bar.\n"174 "- Users are reminded that this is a screening tool only.\n"175 "- Final judgment should always involve human critical thinking."176 )177 178 # ===== About tab =====179 with gr.Tab("About"):180 header()181 with gr.Group(elem_classes=["glass-card"], elem_id="about-intro-card"):182 gr.Markdown(183 "## About CMD\u2011BERT\n"184 "**CMD\u2011BERT: An AI Augmented Linguistic Recognition Model for Cebuano Fake News Detection**\n\n"185 "CMD\u2011BERT is a thesis project in the Department of Computer Engineering at "186 "Cebu Technological University\u2013Main Campus. The tool aims to support Cebuano readers "187 "by highlighting potentially misleading writing patterns in online news and posts."188 )189 with gr.Group(elem_classes=["glass-card"], elem_id="about-thesis-card"):190 gr.Markdown(191 "### Thesis information\n"192 "_A Thesis Project presented to the Faculty of the Department of Computer Engineering_\n\n"193 "Cebu Technological University\u2013Main Campus \n"194 "Cebu City, Philippines \n\n"195 "_In partial fulfillment of the requirements for the degree_ \n"196 "**Bachelor of Science in Computer Engineering**\n\n"197 "**By:** \n"198 "- Cabag, Ronilo Jose Jr. S. \n"199 "- Libron, Andio Mart \n"200 "- Omega, Noel \n\n"201 "**Adviser:** Engr. Jueco, M.Eng. \n"202 "January 2026"203 )204 205 # ===== Feedback tab =====206 with gr.Tab("Feedback"):207 header()208 with gr.Group(elem_classes=["glass-card"], elem_id="fb-intro-card"):209 gr.Markdown(210 "## Feedback and model improvement\n"211 "CMD\u2011BERT is experimental and continuously improving. Your feedback can help "212 "identify model mistakes, usability issues, and opportunities to refine the dataset."213 )214 with gr.Row():215 with gr.Column():216 with gr.Group(elem_classes=["glass-card"], elem_id="fb-form-card"):217 fb_type = gr.Dropdown(218 ["Bug / technical issue", "Model mistake", "UI suggestion", "Other"],219 label="Feedback type",220 )221 fb_text = gr.Textbox(222 lines=6,223 label="Your message or example text",224 placeholder="Describe the issue or paste an example of text the model misclassified.",225 elem_id="fb-textbox",226 )227 fb_email = gr.Textbox(228 label="Email (optional, for follow\u2011up)",229 placeholder="you@example.com",230 elem_id="fb-email-textbox",231 )232 fb_checkbox = gr.Checkbox(233 label="Allow us to use this text anonymously for future model improvements.",234 value=True,235 )236 fb_submit = gr.Button("Submit feedback", elem_classes=["btn-primary-custom"])237 with gr.Column():238 with gr.Group(elem_classes=["glass-card"], elem_id="fb-faq-card"):239 fb_status = gr.Markdown("No feedback submitted yet.")240 gr.Markdown(241 "### FAQ\n"242 "**What happens to my feedback?** \n"243 "It is stored securely and reviewed by the CMD\u2011BERT thesis team.\n\n"244 "**Will CMD\u2011BERT replace human fact\u2011checkers?** \n"245 "No. It is a support tool to encourage critical reading.\n\n"246 "**Who maintains this tool?** \n"247 "The CMD\u2011BERT thesis team at Cebu Technological University\u2013Main Campus."248 )249 250 def save_feedback(ftype, text, email, consent):251 if not text.strip():252 return "Please enter a message before submitting."253 return "Thank you for your feedback! It has been recorded."254 255 fb_submit.click(256 fn=save_feedback,257 inputs=[fb_type, fb_text, fb_email, fb_checkbox],258 outputs=fb_status,259 )260 261if __name__ == "__main__":262 demo.launch(css=custom_css, theme=gr.themes.Soft())263 