-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp_api.py
More file actions
78 lines (59 loc) · 2.37 KB
/
Copy pathapp_api.py
File metadata and controls
78 lines (59 loc) · 2.37 KB
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
75
76
77
78
''' Для cmd
curl -X POST http://127.0.0.1:5000/predict_model -H "Content-Type: application/json" -d "{\"text\":\"Я хуйня\"}"
'''
from fastapi import FastAPI, Request, HTTPException
import dill
import pandas as pd
from pydantic import BaseModel
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from fastapi.responses import HTMLResponse
import nltk
import string
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from nltk.stem import SnowballStemmer
nltk.download('punkt')
nltk.download('punkt_tab')
nltk.download('stopwords')
app = FastAPI()
# Настройка статических файлов (CSS/JS)
app.mount("/static", StaticFiles(directory="static"), name="static")
# Настройка шаблонов Jinja2 (HTML)
templates = Jinja2Templates(directory="templates")
snowball = SnowballStemmer(language="russian")
russian_stop_words = stopwords.words("russian")
def tokenize_sentence(sentence: str, remove_stop_words: bool = True):
tokens = word_tokenize(sentence, language="russian")
tokens = [i for i in tokens if i not in string.punctuation]
if remove_stop_words:
tokens = [i for i in tokens if i not in russian_stop_words]
tokens = [snowball.stem(i) for i in tokens]
return tokens
# Загрузка модели (с проверкой)
with open('model.pkl', 'rb') as f:
model = dill.load(f)
# Глобальный счетчик запросов
request_count = 0
# Модель для валидации входных данных
class PredictionInput(BaseModel):
text: str # Текст для классификации
@app.get("/", response_class=HTMLResponse)
async def read_root(request: Request):
return templates.TemplateResponse("index.html", {"request": request})
@app.get("/stats")
def stats():
return {"request_count": request_count}
@app.get("/health")
def health():
return {"status": "OK"}
@app.post("/predict_model")
def predict_model(input_data: PredictionInput):
global request_count
request_count += 1
predictions = model.predict([input_data.text])
# Формируем ответ
return {"Вывод:": "Это плохой комментарий" if predictions[0] == 1 else "Это обычный комментарий"}
if __name__ == '__main__':
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=5000)