File size: 2,330 Bytes
0770ced | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | import gradio as gr
import torch
import os
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
from huggingface_hub import hf_hub_download
# This points to the repo where you uploaded the .pt files in Phase 1
MODEL_REPO = "ibz18/Model_D_weights"
BASE_MODEL = "csebuetnlp/banglat5"
hf_token = os.environ.get("HF_TOKEN")
print("1. Downloading .pt file...")
abstracter_rl_path = hf_hub_download(
repo_id=MODEL_REPO,
filename="abstracter_rl.pt",
token=hf_token
)
print("2. Loading tokenizer and base model...")
tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL)
model = AutoModelForSeq2SeqLM.from_pretrained(BASE_MODEL)
print("3. Resizing embeddings...")
model.resize_token_embeddings(len(tokenizer))
print("4. Injecting .pt weights into memory...")
checkpoint = torch.load(abstracter_rl_path, map_location="cpu", weights_only=True)
if isinstance(checkpoint, dict) and "state_dict" in checkpoint:
state_dict = checkpoint["state_dict"]
else:
state_dict = checkpoint
model.load_state_dict(state_dict, strict=False)
model.eval()
def generate_summary(text):
if not text.strip():
return "Please enter Bangla text."
try:
inputs = tokenizer(text, return_tensors="pt", truncation=True, max_length=512)
with torch.no_grad():
output_ids = model.generate(
**inputs,
max_new_tokens=128,
do_sample=False,
num_beams=2,
repetition_penalty=2.5,
early_stopping=True,
decoder_start_token_id=tokenizer.pad_token_id,
eos_token_id=tokenizer.eos_token_id,
pad_token_id=tokenizer.pad_token_id
)
summary = tokenizer.decode(output_ids[0], skip_special_tokens=True)
return summary if summary.strip() else "ERROR: Empty string"
except Exception as e:
return f"CRASH ERROR: {str(e)}"
# --- INTERFACE WITH NEW NAME ---
demo = gr.Interface(
fn=generate_summary,
inputs=gr.Textbox(lines=8, label="Input Bangla Text", placeholder="এখানে আপনার বাংলা টেক্সট দিন..."),
outputs=gr.Textbox(label="Generated Summary"),
title="Model_D",
description="Live testing interface for Model_D"
)
demo.launch()
|