Spaces:
Sleeping
Sleeping
Update app.py
Browse files1232345677889101112131415161314151617181917181920202223242122232426272829303125262733343536373828293031323334353637404138394041434445464243444546474848495051525354555657585949616263645051525354555657585960616263646568697071727374756667687769798081828384858687888990919293949596707172from fastapi import FastAPI, Requestfrom transformers import BertModel, BertForSequenceClassification, AutoTokenizerfrom huggingface_hub import hf_hub_downloadfrom pydantic import BaseModelimport torchimport pickleimport gluonnlp as nlpimport numpy as npimport osimport sysimport psutilfrom kobert_tokenizer import KoBERTTokenizerfrom model import BERTClassifierfrom dataset import BERTDatasetfrom transformers import BertModelimport logging
app = FastAPI()device = torch.device("cpu")
# category.pkl λ‘λtry: with open("category.pkl", "rb") as f: category = pickle.load(f)# β
category λ‘λwith open("category.pkl", "rb") as f: category = pickle.load(f) print("β
category.pkl λ‘λ μ±κ³΅.")except FileNotFoundError: print("β Error: category.pkl νμΌμ μ°Ύμ μ μμ΅λλ€.") sys.exit(1)
# ν ν¬λμ΄μ λ‘λtokenizer = AutoTokenizer.from_pretrained("skt/kobert-base-v1")print("β
ν ν¬λμ΄μ λ‘λ μ±κ³΅.")# β
vocab λ‘λwith open("vocab.pkl", "rb") as f: vocab = pickle.load(f)
class CustomClassifier(torch.nn.Module): def __init__(self): super().__init__() # μ μνλ ꡬ쑰 κ·Έλλ‘ λ³΅μν΄μΌ ν¨ self.bert = BertModel.from_pretrained("skt/kobert-base-v1") self.classifier = torch.nn.Linear(768, len(category))# β
ν ν¬λμ΄μ tokenizer = KoBERTTokenizer.from_pretrained('skt/kobert-base-v1')
def forward(self, input_ids, attention_mask=None, token_type_ids=None): outputs = self.bert(input_ids=input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids) pooled_output = outputs[1] # CLS ν ν° return self.classifier(pooled_output)# β
λͺ¨λΈ λ‘λmodel = BERTClassifier( BertModel.from_pretrained('skt/kobert-base-v1'), dr_rate=0.5, num_classes=len(category))model.load_state_dict(torch.load("textClassifierModel.pt", map_location=device))model.to(device)model.eval()
HF_MODEL_REPO_ID = "hiddenFront/TextClassifier"HF_MODEL_FILENAME = "textClassifierModel.pt"# β
λ°μ΄ν°μ
μμ±μ νμν νλΌλ―Έν°max_len = 64batch_size = 32
# λ©λͺ¨λ¦¬ μΈ‘μ μ process = psutil.Process(os.getpid())mem_before = process.memory_info().rss / (1024 * 1024)print(f"π¦ λͺ¨λΈ λ€μ΄λ‘λ μ λ©λͺ¨λ¦¬ μ¬μ©λ: {mem_before:.2f} MB")# β
μμΈ‘ ν¨μdef predict(predict_sentence): data = [predict_sentence, '0'] dataset_another = [data] another_test = BERTDataset(dataset_another, 0, 1, tokenizer, vocab, max_len, True, False) test_dataLoader = torch.utils.data.DataLoader(another_test, batch_size=batch_size, num_workers=0)
# λͺ¨λΈ λ‘λtry: model_path = hf_hub_download(repo_id=HF_MODEL_REPO_ID, filename=HF_MODEL_FILENAME) print(f"β
λͺ¨λΈ νμΌ λ€μ΄λ‘λ μ±κ³΅: {model_path}")
state_dict = torch.load(model_path, map_location=device) model = BertForSequenceClassification.from_pretrained( "skt/kobert-base-v1", num_labels=len(category), state_dict=state_dict, ) model.to(device) model.eval() print("β
λͺ¨λΈ λ‘λ λ° μ€λΉ μλ£.")except Exception as e: print(f"β Error: λͺ¨λΈ λ‘λ μ€ μ€λ₯ λ°μ: {e}") sys.exit(1) for batch_id, (token_ids, valid_length, segment_ids, label) in enumerate(test_dataLoader): token_ids = token_ids.long().to(device) segment_ids = segment_ids.long().to(device)
out = model(token_ids, valid_length, segment_ids) test_eval = [] for i in out: logits = i.detach().cpu().numpy() test_eval.append(list(category.keys())[np.argmax(logits)]) return test_eval[0]
# β
μλν¬μΈνΈ μ μclass InputText(BaseModel): text: str
@app.get("/")def root(request: Request): client_host = request.client.host client_port = request.client.port return { "message": "Text Classification API is running!", "client_ip": client_host, "client_port": client_port }def root(): return {"message": "Text Classification API (KoBERT)"}
# μμΈ‘ API@app.post("/predict")async def predict_api(request: Request): data = await request.json() text = data.get("text") print("request date", data); if not text: return {"error": "No text provided", "classification": "null"}
encoded = tokenizer.encode_plus( text, max_length=64, padding='max_length', truncation=True, return_tensors='pt' )
with torch.no_grad(): outputs = model(**encoded) probs = torch.nn.functional.softmax(outputs.logits, dim=1) predicted = torch.argmax(probs, dim=1).item()
label = list(category.keys())[predicted] return {"text": text, "classification": label}async def predict_route(item: InputText): result = predict(item.text) return {"text": item.text, "classification": result}app.py+52-76