Spaces:
Sleeping
Sleeping
Download app.py from Khoa/generic-sentiment: direct link, hf CLI and curl.
- Browser
- Download file 12 kB
-
https://huggingface.co/spaces/Khoa/generic-sentiment/resolve/main/app.py
- Command line
-
hf download hf://spaces/Khoa/generic-sentiment/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Khoa/generic-sentiment/resolve/main/app.py
12 kB
| import os | |
| import re | |
| import tempfile | |
| from functools import lru_cache | |
| import spaces | |
| import gradio as gr | |
| import pandas as pd | |
| import torch | |
| from transformers import AutoModelForSequenceClassification, AutoTokenizer | |
| REQUIRED_COLUMNS = ("Title", "Content", "Description", "Type") | |
| DEFAULT_MODEL = os.environ.get( | |
| "SENTIMENT_MODEL_PATH", "5CD-AI/Vietnamese-Sentiment-visobert" | |
| ) | |
| # Ngưỡng confidence: chỉ giữ nhãn model khi confidence > ngưỡng, ngược lại -> neutral | |
| DEFAULT_CONFIDENCE_THRESHOLD = float( | |
| os.environ.get("SENTIMENT_CONFIDENCE_THRESHOLD", "0.75") | |
| ) | |
| RAW_TO_LABEL = { | |
| "NEG": "negative", | |
| "NEGATIVE": "negative", | |
| "LABEL_0": "negative", | |
| "POS": "positive", | |
| "POSITIVE": "positive", | |
| "LABEL_1": "positive", | |
| "NEU": "neutral", | |
| "NEUTRAL": "neutral", | |
| "LABEL_2": "neutral", | |
| } | |
| def get_device(): | |
| if torch.cuda.is_available(): | |
| return torch.device("cuda") | |
| if hasattr(torch.backends, "mps") and torch.backends.mps.is_available(): | |
| return torch.device("mps") | |
| return torch.device("cpu") | |
| def load_sentiment_model(model_path: str): | |
| """Cache loaded models so subsequent runs don't reload model weights.""" | |
| device = get_device() | |
| tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=True) | |
| model = AutoModelForSequenceClassification.from_pretrained(model_path) | |
| model.to(device) | |
| model.eval() | |
| use_fp16 = os.environ.get("SENTIMENT_FP16", "1") != "0" | |
| if use_fp16 and device.type == "cuda": | |
| model.half() | |
| labels = {} | |
| for idx, raw_label in model.config.id2label.items(): | |
| normalized = str(raw_label).strip().upper() | |
| labels[int(idx)] = RAW_TO_LABEL.get(normalized, None) | |
| # The default ViSoBERT model uses 0=NEG, 1=POS, 2=NEU. | |
| # Fall back to that order if the repository has generic LABEL_n names. | |
| if any(value is None for value in labels.values()): | |
| labels = {0: "negative", 1: "positive", 2: "neutral"} | |
| return tokenizer, model, device, labels | |
| def get_doc_type(type_value): | |
| value = str(type_value).strip().lower() | |
| if value.endswith("comment"): | |
| return "comment" | |
| if value.endswith("topic"): | |
| return "topic" | |
| return "unknown" | |
| def clean_cell(value): | |
| if pd.isna(value): | |
| return "" | |
| return str(value).strip() | |
| def build_text(row, doc_type): | |
| if doc_type == "comment": | |
| return clean_cell(row.get("Content", "")) | |
| parts = [ | |
| clean_cell(row.get("Content", "")), | |
| clean_cell(row.get("Title", "")), | |
| clean_cell(row.get("Description", "")), | |
| ] | |
| return " . ".join(part for part in parts if part) | |
| def apply_confidence_threshold(label, confidence, threshold): | |
| """Chỉ giữ nhãn model khi confidence > threshold, ngược lại trả về neutral.""" | |
| if confidence > threshold: | |
| return label | |
| return "neutral" | |
| _keyword_cache = {} | |
| def apply_keyword_fallback(label, confidence, text, keywords): | |
| if label != "negative": | |
| return label, confidence | |
| if not keywords: | |
| return "neutral", confidence | |
| for keyword in keywords: | |
| if not keyword: | |
| continue | |
| pattern = _keyword_cache.get(keyword) | |
| if pattern is None: | |
| pattern = re.compile(re.escape(keyword), re.IGNORECASE) | |
| _keyword_cache[keyword] = pattern | |
| if pattern.search(text): | |
| return label, confidence | |
| return "neutral", confidence | |
| def predict_batch(texts, tokenizer, model, device, label_map, max_length): | |
| if not texts: | |
| return [] | |
| # Sort by length to reduce padding, then restore original order. | |
| order = sorted(range(len(texts)), key=lambda i: len(texts[i]), reverse=True) | |
| sorted_texts = [texts[i] for i in order] | |
| inputs = tokenizer( | |
| sorted_texts, | |
| padding=True, | |
| truncation=True, | |
| max_length=max_length, | |
| return_tensors="pt", | |
| ) | |
| inputs = {key: value.to(device) for key, value in inputs.items()} | |
| with torch.inference_mode(): | |
| outputs = model(**inputs) | |
| probabilities = torch.nn.functional.softmax(outputs.logits.float(), dim=-1) | |
| confidences, predictions = torch.max(probabilities, dim=-1) | |
| sorted_results = [ | |
| (label_map.get(pred, "neutral"), float(conf)) | |
| for pred, conf in zip(predictions.tolist(), confidences.tolist()) | |
| ] | |
| results = [None] * len(texts) | |
| for sorted_pos, original_pos in enumerate(order): | |
| results[original_pos] = sorted_results[sorted_pos] | |
| return results | |
| def process_dataframe( | |
| df, | |
| model_path, | |
| batch_size, | |
| max_length, | |
| confidence_threshold, | |
| skip_keyword_check, | |
| main_keywords, | |
| progress=gr.Progress(), | |
| ): | |
| missing = [column for column in REQUIRED_COLUMNS if column not in df.columns] | |
| if missing: | |
| raise gr.Error("File thiếu cột bắt buộc: " + ", ".join(missing)) | |
| # Reset index để bảo đảm vị trí kết quả khớp với dữ liệu đầu vào. | |
| df = df.copy().reset_index(drop=True) | |
| tokenizer, model, device, label_map = load_sentiment_model(model_path) | |
| keywords = [ | |
| item.strip() for item in (main_keywords or "").split(",") if item.strip() | |
| ] | |
| sentiments = [""] * len(df) | |
| confidences = [None] * len(df) | |
| pending_indices = [] | |
| pending_texts = [] | |
| unknown_types = 0 | |
| empty_content = 0 | |
| low_confidence = 0 | |
| # Chuẩn bị nội dung cần phân loại. | |
| for position in range(len(df)): | |
| row = df.iloc[position] | |
| doc_type = get_doc_type(row.get("Type")) | |
| if doc_type == "unknown": | |
| unknown_types += 1 | |
| continue | |
| text = build_text(row, doc_type) | |
| if not text: | |
| empty_content += 1 | |
| continue | |
| pending_indices.append(position) | |
| pending_texts.append(text) | |
| total = len(pending_texts) | |
| progress(0, desc="Đang chuẩn bị dữ liệu...") | |
| # Phân loại theo batch. | |
| for start in range(0, total, batch_size): | |
| batch_texts = pending_texts[start:start + batch_size] | |
| batch_indices = pending_indices[start:start + batch_size] | |
| results = predict_batch( | |
| batch_texts, tokenizer, model, device, label_map, max_length | |
| ) | |
| for index, text, (label, confidence) in zip( | |
| batch_indices, batch_texts, results | |
| ): | |
| # 1) Ngưỡng confidence: <= threshold -> neutral | |
| thresholded = apply_confidence_threshold( | |
| label, confidence, confidence_threshold | |
| ) | |
| if thresholded != label: | |
| low_confidence += 1 | |
| label = thresholded | |
| # 2) Keyword fallback (nếu bật) | |
| if not skip_keyword_check: | |
| label, confidence = apply_keyword_fallback( | |
| label, confidence, text, keywords | |
| ) | |
| sentiments[index] = label | |
| confidences[index] = round(confidence, 4) | |
| completed = min(start + len(batch_texts), total) | |
| progress( | |
| completed / max(total, 1), | |
| desc=f"Đang phân tích: {completed:,}/{total:,} dòng", | |
| ) | |
| # Thêm hoặc cập nhật cột Sentiment + Confidence. | |
| df["Sentiment"] = sentiments | |
| df["Confidence"] = confidences | |
| counts = df["Sentiment"].value_counts() | |
| summary = [ | |
| f"**Thiết bị:** `{device}`", | |
| f"**Model:** `{model_path}`", | |
| f"**Ngưỡng confidence:** > {confidence_threshold:.2f}", | |
| f"**Tổng số dòng:** {len(df):,}", | |
| f"**Đã phân tích:** {total:,}", | |
| f"**Chuyển neutral do confidence thấp:** {low_confidence:,}", | |
| f"**Bỏ trống do Type không hợp lệ:** {unknown_types:,}", | |
| f"**Bỏ trống do không có nội dung:** {empty_content:,}", | |
| "", | |
| "**Thống kê sentiment:**", | |
| ] | |
| for label in ("positive", "neutral", "negative"): | |
| summary.append(f"- `{label}`: {int(counts.get(label, 0)):,}") | |
| return df, "\n".join(summary) | |
| def run_app( | |
| file, | |
| model_path, | |
| batch_size, | |
| max_length, | |
| confidence_threshold, | |
| skip_keyword_check, | |
| keywords, | |
| ): | |
| if file is None: | |
| raise gr.Error("Vui lòng upload file Excel trước.") | |
| extension = os.path.splitext(file)[1].lower() | |
| if extension not in (".xlsx", ".xls"): | |
| raise gr.Error("Chỉ hỗ trợ file Excel .xlsx hoặc .xls.") | |
| try: | |
| df = pd.read_excel(file, sheet_name=0) | |
| except Exception as exc: | |
| raise gr.Error(f"Không đọc được file Excel: {exc}") | |
| result_df, summary = process_dataframe( | |
| df=df, | |
| model_path=(model_path or DEFAULT_MODEL).strip(), | |
| batch_size=int(batch_size), | |
| max_length=int(max_length), | |
| confidence_threshold=float(confidence_threshold), | |
| skip_keyword_check=skip_keyword_check, | |
| main_keywords=keywords, | |
| ) | |
| output_dir = tempfile.mkdtemp(prefix="sentiment_") | |
| input_name = os.path.splitext(os.path.basename(file))[0] | |
| output_path = os.path.join(output_dir, f"{input_name}_sentiment.xlsx") | |
| result_df.to_excel(output_path, index=False, engine="openpyxl") | |
| return summary, output_path, result_df.head(20) | |
| with gr.Blocks(title="Vietnamese Sentiment Analyzer", theme=gr.themes.Soft()) as demo: | |
| gr.Markdown( | |
| """ | |
| # Vietnamese Sentiment Analyzer | |
| Upload file Excel để phân loại sentiment bằng ViSoBERT. File đầu ra giữ | |
| nguyên các cột dữ liệu và thêm/cập nhật cột `Sentiment`, `Confidence`. | |
| **Cột bắt buộc:** `Title`, `Content`, `Description`, `Type`. | |
| Nhãn chỉ được giữ khi **confidence > ngưỡng** (mặc định 0.75), ngược lại trả về `neutral`. | |
| """ | |
| ) | |
| with gr.Row(): | |
| file_input = gr.File( | |
| label="File Excel đầu vào", | |
| file_types=[".xlsx", ".xls"], | |
| type="filepath", | |
| ) | |
| model_path = gr.Textbox( | |
| label="Hugging Face model ID hoặc đường dẫn model", | |
| value=DEFAULT_MODEL, | |
| placeholder="5CD-AI/Vietnamese-Sentiment-visobert", | |
| ) | |
| with gr.Accordion("Cấu hình nâng cao", open=False): | |
| with gr.Row(): | |
| batch_size = gr.Slider( | |
| minimum=1, maximum=256, value=32, step=1, label="Batch size" | |
| ) | |
| max_length = gr.Slider( | |
| minimum=32, maximum=512, value=256, step=32, label="Max token length" | |
| ) | |
| confidence_threshold = gr.Slider( | |
| minimum=0.0, | |
| maximum=0.99, | |
| value=DEFAULT_CONFIDENCE_THRESHOLD, | |
| step=0.01, | |
| label="Ngưỡng confidence", | |
| info="Confidence <= ngưỡng sẽ trả về neutral.", | |
| ) | |
| skip_keyword_check = gr.Checkbox( | |
| value=True, | |
| label="Bỏ qua keyword fallback (giữ nguyên nhãn model dự đoán)", | |
| ) | |
| keywords = gr.Textbox( | |
| label="Main keywords (phân cách bằng dấu phẩy)", | |
| placeholder="ShopeePay, Shopee, ví điện tử", | |
| info="Chỉ áp dụng khi bỏ chọn keyword fallback ở trên. Negative không chứa keyword sẽ chuyển thành neutral.", | |
| ) | |
| run_button = gr.Button("Chạy sentiment", variant="primary") | |
| summary_output = gr.Markdown(label="Kết quả") | |
| file_output = gr.File(label="Tải file Excel kết quả") | |
| preview_output = gr.Dataframe(label="Xem trước 20 dòng", interactive=False) | |
| run_button.click( | |
| fn=run_app, | |
| inputs=[ | |
| file_input, | |
| model_path, | |
| batch_size, | |
| max_length, | |
| confidence_threshold, | |
| skip_keyword_check, | |
| keywords, | |
| ], | |
| outputs=[summary_output, file_output, preview_output], | |
| ) | |
| if __name__ == "__main__": | |
| demo.launch(server_name="0.0.0.0", server_port=7860, ssr_mode=False) |