isspek commited on
Commit
2cfe868
1 Parent(s): 60d9ff0

Upload main.py

Browse files
Files changed (1) hide show
  1. main.py +49 -0
main.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pydantic import BaseModel, validator
2
+ from peft import PeftModel, PeftConfig
3
+ from transformers import T5ForConditionalGeneration, AutoTokenizer
4
+ from fastapi import FastAPI, Request
5
+ from fastapi.middleware.cors import CORSMiddleware
6
+
7
+ app = FastAPI()
8
+
9
+ origins = ["*"]
10
+ app.add_middleware(
11
+ CORSMiddleware,
12
+ allow_origins=origins,
13
+ allow_credentials=True,
14
+ allow_methods=["*"],
15
+ allow_headers=["*"]
16
+ )
17
+
18
+
19
+
20
+ peft_model_id = "deutsche-welle/t5_large_peft_wnc_debiaser"
21
+ config = PeftConfig.from_pretrained(peft_model_id)
22
+
23
+ model = T5ForConditionalGeneration.from_pretrained(config.base_model_name_or_path)
24
+ tokenizer = AutoTokenizer.from_pretrained(config.base_model_name_or_path)
25
+
26
+ model = PeftModel.from_pretrained(model, peft_model_id)
27
+ model.eval()
28
+
29
+
30
+ def prepare_input(sentence: str):
31
+ input_ids = tokenizer(sentence, max_length=256, return_tensors="pt").input_ids
32
+ return input_ids
33
+
34
+
35
+ def inference(sentence: str) -> str:
36
+ input_data = prepare_input(sentence=sentence)
37
+ input_data = input_data.to(model.device)
38
+ outputs = model.generate(inputs=input_data, max_length=256)
39
+ result = tokenizer.decode(token_ids=outputs[0], skip_special_tokens=True)
40
+ return result
41
+
42
+ class Response(BaseModel):
43
+ generated_text: str
44
+
45
+
46
+ @app.get("/debias", response_model=Response)
47
+ def predict_subjectivity(sentence: str):
48
+ result = inference(f"debias: {sentence} </s>")
49
+ return {"generated_text": result}