Afwa/Binary-SoftwareRequirement-Classification
1
1import gradio as gr2from transformers import DistilBertForSequenceClassification, DistilBertTokenizerFast3import torch4import re5 6# Load model dan tokenizer dari Hugging Face Hub7model = DistilBertForSequenceClassification.from_pretrained(8 "Afwa/Binary-SoftwareRequirement-DistilBERT-TPE-Model"9)10tokenizer = DistilBertTokenizerFast.from_pretrained(11 "Afwa/Binary-SoftwareRequirement-DistilBERT-TPE-Model"12)13 14# Karena config.json tidak punya id2label, kita buat manual15id2label = {0: "Functional", 1: "Non-Functional"}16 17def is_gibberish(text: str) -> bool:18 """Deteksi input ngaco/random."""19 # Hanya angka/simbol tanpa huruf20 if not re.search(r"[a-zA-Z]", text):21 return True22 # Terlalu pendek (< 3 kata berarti banget)23 if len(text.split()) < 3:24 return True25 return False26 27def predict(text):28 # Cek input kosong29 if not text.strip():30 return "Please enter text"31 32 # Cek input ngaco33 if is_gibberish(text):34 return "Unrecognized input"35 36 # Tokenisasi input37 inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True)38 39 # Forward pass40 with torch.no_grad():41 outputs = model(**inputs)42 43 # Ambil probabilitas44 probs = torch.nn.functional.softmax(outputs.logits, dim=-1)[0]45 46 # Ambil label top-147 pred_id = torch.argmax(probs).item()48 pred_label = id2label[pred_id]49 50 return pred_label51 52# Gradio interface53demo = gr.Interface(54 fn=predict,55 inputs=gr.Textbox(lines=3, placeholder="Enter your requirements here..."),56 # outputs=gr.Textbox(label="Prediction"), # cuma tampilkan label57 outputs=gr.Label(),58 title="Binary Classification Software Requirements",59 description="This DistilBERT model (optimized with TPE) classifies requirements into **Functional** or **Non-Functional**. Note: the model is trained on English text only.",60 flagging_mode="never"61)62 63demo.launch()