Spaces:
Paused
Paused
Update app.py
Browse files14 unmodified lines15161718192021222324252627282930313233343536373839404142434445464748495051522 unmodified lines5556575859606162636414 unmodified linestokenizer_base = Tokenizer(charset)def get_transform(img_size):transforms = []transforms.extend([T.Resize(img_size, T.InterpolationMode.BICUBIC),T.ToTensor(),T.Normalize(0.5, 0.5)])return T.Compose(transforms)def to_numpy(tensor):return tensor.detach().cpu().numpy() if tensor.requires_grad else tensor.cpu().numpy()def initialize_model(model_file):transform = get_transform(img_size)# Загрузка модели ONNXonnx_model = onnx.load(model_file)onnx.checker.check_model(onnx_model)ort_session = rt.InferenceSession(model_file)return transform, ort_sessiontransform, ort_session = initialize_model(model_file=model_file)# Создаем FastAPI приложениеapp = FastAPI()# Функция для получения текстаdef get_text(img_org):x = transform(img_org.convert('RGB')).unsqueeze(0)ort_inputs = {ort_session.get_inputs()[0].name: to_numpy(x)}logits = ort_session.run(None, ort_inputs)[0]probs = torch.tensor(logits).softmax(-1)preds, _ = tokenizer_base.decode(probs)return preds[0]# Маршрут для обработки POST-запросов с изображениями@app.post("/predict")2 unmodified lines# Получаем изображение из запросаimage_bytes = await file.read()img = Image.open(BytesIO(image_bytes))# Получаем текст с изображенияresult = get_text(img)# Возвращаем распознанный текстreturn JSONResponse(content={"text": result})except Exception as e:14 unmodified lines15161718192021222324252627282930313233343536373839404142434445464748495051525354555657582 unmodified lines6162636465666768697014 unmodified linestokenizer_base = Tokenizer(charset)def get_transform(img_size):transforms = [T.Resize(img_size, T.InterpolationMode.BICUBIC),T.ToTensor(),T.Normalize(0.5, 0.5)]return T.Compose(transforms)def to_numpy(tensor):return tensor.detach().cpu().numpy() if tensor.requires_grad else tensor.cpu().numpy()def initialize_model(model_file):try:# Загрузка модели ONNXonnx_model = onnx.load(model_file)onnx.checker.check_model(onnx_model)ort_session = rt.InferenceSession(model_file)transform = get_transform(img_size)return transform, ort_sessionexcept Exception as e:raise RuntimeError(f"Ошибка при инициализации модели: {e}")# Инициализация моделиtransform, ort_session = initialize_model(model_file)# Создаем FastAPI приложениеapp = FastAPI()# Функция для получения текстаdef get_text(img_org):try:x = transform(img_org.convert('RGB')).unsqueeze(0)ort_inputs = {ort_session.get_inputs()[0].name: to_numpy(x)}logits = ort_session.run(None, ort_inputs)[0]probs = torch.tensor(logits).softmax(-1)preds, _ = tokenizer_base.decode(probs)return preds[0]except Exception as e:raise RuntimeError(f"Ошибка при обработке изображения: {e}")# Маршрут для обработки POST-запросов с изображениями@app.post("/predict")2 unmodified lines# Получаем изображение из запросаimage_bytes = await file.read()img = Image.open(BytesIO(image_bytes))# Получаем текст с изображенияresult = get_text(img)# Возвращаем распознанный текстreturn JSONResponse(content={"text": result})except Exception as e:
app.py+24-18