tddf commited on
Commit
a345f45
·
verified ·
1 Parent(s): 22cde00

Update Main.py

Browse files
Files changed (1) hide show
  1. Main.py +17 -28
Main.py CHANGED
@@ -5,6 +5,7 @@ import torch
5
  from transformers import LightOnOcrForConditionalGeneration, LightOnOcrProcessor
6
  from PIL import Image
7
 
 
8
  os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"
9
 
10
  st.set_page_config(
@@ -60,7 +61,7 @@ def load_image():
60
  return Image.open(io.BytesIO(image_data)).convert('RGB')
61
  return None
62
 
63
- # ==================== Главный интерфейс ====================
64
  st.markdown('<div class="header-emoji">📄✨</div>', unsafe_allow_html=True)
65
  st.title("LightOnOCR")
66
  st.markdown("**Распознавание текста с изображений**")
@@ -78,42 +79,34 @@ if st.button("🔍 Распознать текст", use_container_width=True, t
78
  if img is None:
79
  st.error("Сначала загрузите изображение")
80
  else:
81
- with st.spinner("Распознавание текста... (может занять 5–30 сек на CPU)"):
82
 
 
83
  conversation = [
84
  {
85
  "role": "user",
86
  "content": [
87
  {"type": "image"},
88
- {"type": "text", "text": "Extract ALL visible text from the image as accurately as possible. Include every word, number, and line. Preserve formatting and tables."}
89
  ]
90
  }
91
  ]
92
 
93
- # Шаблон чата
94
  inputs = processor.apply_chat_template(
95
  conversation,
96
  add_generation_prompt=True,
97
  tokenize=True,
98
  return_dict=True,
99
- return_tensors="pt"
 
100
  )
101
 
102
- # Обработка изображения
103
- image_inputs = processor.image_processor(img, return_tensors="pt")
104
- pixel_values = image_inputs.pixel_values.to(device=device, dtype=dtype)
105
-
106
- # Размеры изображения (критично для модели)
107
- height, width = img.size[1], img.size[0] # PIL: (width, height) → height, width
108
- image_sizes = torch.tensor([[height, width]], dtype=torch.long, device=device)
109
-
110
- inputs["pixel_values"] = pixel_values
111
- inputs["image_sizes"] = image_sizes
112
-
113
- # Перенос остальных тензоров
114
- for k, v in inputs.items():
115
- if isinstance(v, torch.Tensor) and k not in ["pixel_values", "image_sizes"]:
116
- inputs[k] = v.to(device=device)
117
 
118
  # Генерация
119
  output_ids = model.generate(
@@ -126,22 +119,18 @@ if st.button("🔍 Распознать текст", use_container_width=True, t
126
  eos_token_id=processor.tokenizer.eos_token_id,
127
  )
128
 
129
- # Извлекаем только сгенерированную часть
130
  prompt_length = inputs["input_ids"].shape[1]
131
  generated_ids = output_ids[0, prompt_length:]
132
-
133
  generated_text = processor.decode(
134
  generated_ids,
135
  skip_special_tokens=True,
136
  clean_up_tokenization_spaces=True
137
  ).strip()
138
 
139
- # Отладка (временно показываем длину)
140
- st.info(f"Сгенерировано токенов: {len(generated_ids)} | Длина текста: {len(generated_text)} символов")
141
-
142
- if not generated_text or len(generated_text) < 5:
143
- st.warning("Модель вернула очень короткий или пустой текст. Попробуйте другое изображение с чётким английским текстом.")
144
- st.code("Результат пустой или слишком короткий.", language=None)
145
  else:
146
  st.success("✅ Распознавание завершено!")
147
  st.markdown('<div class="result-box">', unsafe_allow_html=True)
 
5
  from transformers import LightOnOcrForConditionalGeneration, LightOnOcrProcessor
6
  from PIL import Image
7
 
8
+ # Ускоряем скачивание
9
  os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"
10
 
11
  st.set_page_config(
 
61
  return Image.open(io.BytesIO(image_data)).convert('RGB')
62
  return None
63
 
64
+ # ==================== Интерфейс ====================
65
  st.markdown('<div class="header-emoji">📄✨</div>', unsafe_allow_html=True)
66
  st.title("LightOnOCR")
67
  st.markdown("**Распознавание текста с изображений**")
 
79
  if img is None:
80
  st.error("Сначала загрузите изображение")
81
  else:
82
+ with st.spinner("Распознавание текста... (5–30 сек на CPU)"):
83
 
84
+ # Правильный формат разговора (как в официальных примерах)
85
  conversation = [
86
  {
87
  "role": "user",
88
  "content": [
89
  {"type": "image"},
90
+ {"type": "text", "text": "Extract all the text from this image as accurately as possible. Preserve line breaks, formatting and tables."}
91
  ]
92
  }
93
  ]
94
 
95
+ # Применяем шаблон + передаём само изображение
96
  inputs = processor.apply_chat_template(
97
  conversation,
98
  add_generation_prompt=True,
99
  tokenize=True,
100
  return_dict=True,
101
+ return_tensors="pt",
102
+ images=img # ← Это ключевой момент
103
  )
104
 
105
+ # Переносим все тензоры на устройство
106
+ inputs = {
107
+ k: (v.to(device=device, dtype=dtype) if v.is_floating_point() else v.to(device))
108
+ for k, v in inputs.items()
109
+ }
 
 
 
 
 
 
 
 
 
 
110
 
111
  # Генерация
112
  output_ids = model.generate(
 
119
  eos_token_id=processor.tokenizer.eos_token_id,
120
  )
121
 
122
+ # Убираем промпт, оставляем только сгенерированный текст
123
  prompt_length = inputs["input_ids"].shape[1]
124
  generated_ids = output_ids[0, prompt_length:]
125
+
126
  generated_text = processor.decode(
127
  generated_ids,
128
  skip_special_tokens=True,
129
  clean_up_tokenization_spaces=True
130
  ).strip()
131
 
132
+ if not generated_text:
133
+ st.warning("Модель не смогла извлечь текст. Попробуйте более чёткое изображение с английски�� текстом.")
 
 
 
 
134
  else:
135
  st.success("✅ Распознавание завершено!")
136
  st.markdown('<div class="result-box">', unsafe_allow_html=True)