Acetde commited on
Commit
a1a2e19
·
verified ·
1 Parent(s): 9269f29

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +24 -18
app.py CHANGED
@@ -15,38 +15,44 @@ charset = r"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!\"#$%
15
  tokenizer_base = Tokenizer(charset)
16
 
17
  def get_transform(img_size):
18
- transforms = []
19
- transforms.extend([
20
  T.Resize(img_size, T.InterpolationMode.BICUBIC),
21
  T.ToTensor(),
22
  T.Normalize(0.5, 0.5)
23
- ])
24
  return T.Compose(transforms)
25
 
26
  def to_numpy(tensor):
27
  return tensor.detach().cpu().numpy() if tensor.requires_grad else tensor.cpu().numpy()
28
 
29
  def initialize_model(model_file):
30
- transform = get_transform(img_size)
31
- # Загрузка модели ONNX
32
- onnx_model = onnx.load(model_file)
33
- onnx.checker.check_model(onnx_model)
34
- ort_session = rt.InferenceSession(model_file)
35
- return transform, ort_session
 
 
 
36
 
37
- transform, ort_session = initialize_model(model_file=model_file)
 
38
 
39
  # Создаем FastAPI приложение
40
  app = FastAPI()
41
 
42
  # Функция для получения текста
43
  def get_text(img_org):
44
- x = transform(img_org.convert('RGB')).unsqueeze(0)
45
- ort_inputs = {ort_session.get_inputs()[0].name: to_numpy(x)}
46
- logits = ort_session.run(None, ort_inputs)[0]
47
- probs = torch.tensor(logits).softmax(-1)
48
- preds, _ = tokenizer_base.decode(probs)
49
- return preds[0]
 
 
 
50
 
51
  # Маршрут для обработки POST-запросов с изображениями
52
  @app.post("/predict")
@@ -55,10 +61,10 @@ async def predict(file: UploadFile = File(...)):
55
  # Получаем изображение из запроса
56
  image_bytes = await file.read()
57
  img = Image.open(BytesIO(image_bytes))
58
-
59
  # Получаем текст с изображения
60
  result = get_text(img)
61
-
62
  # Возвращаем распознанный текст
63
  return JSONResponse(content={"text": result})
64
  except Exception as e:
 
15
  tokenizer_base = Tokenizer(charset)
16
 
17
  def get_transform(img_size):
18
+ transforms = [
 
19
  T.Resize(img_size, T.InterpolationMode.BICUBIC),
20
  T.ToTensor(),
21
  T.Normalize(0.5, 0.5)
22
+ ]
23
  return T.Compose(transforms)
24
 
25
  def to_numpy(tensor):
26
  return tensor.detach().cpu().numpy() if tensor.requires_grad else tensor.cpu().numpy()
27
 
28
  def initialize_model(model_file):
29
+ try:
30
+ # Загрузка модели ONNX
31
+ onnx_model = onnx.load(model_file)
32
+ onnx.checker.check_model(onnx_model)
33
+ ort_session = rt.InferenceSession(model_file)
34
+ transform = get_transform(img_size)
35
+ return transform, ort_session
36
+ except Exception as e:
37
+ raise RuntimeError(f"Ошибка при инициализации модели: {e}")
38
 
39
+ # Инициализация модели
40
+ transform, ort_session = initialize_model(model_file)
41
 
42
  # Создаем FastAPI приложение
43
  app = FastAPI()
44
 
45
  # Функция для получения текста
46
  def get_text(img_org):
47
+ try:
48
+ x = transform(img_org.convert('RGB')).unsqueeze(0)
49
+ ort_inputs = {ort_session.get_inputs()[0].name: to_numpy(x)}
50
+ logits = ort_session.run(None, ort_inputs)[0]
51
+ probs = torch.tensor(logits).softmax(-1)
52
+ preds, _ = tokenizer_base.decode(probs)
53
+ return preds[0]
54
+ except Exception as e:
55
+ raise RuntimeError(f"Ошибка при обработке изображения: {e}")
56
 
57
  # Маршрут для обработки POST-запросов с изображениями
58
  @app.post("/predict")
 
61
  # Получаем изображение из запроса
62
  image_bytes = await file.read()
63
  img = Image.open(BytesIO(image_bytes))
64
+
65
  # Получаем текст с изображения
66
  result = get_text(img)
67
+
68
  # Возвращаем распознанный текст
69
  return JSONResponse(content={"text": result})
70
  except Exception as e: