Update Main.py
Browse files
Main.py
CHANGED
|
@@ -5,7 +5,6 @@ import torch
|
|
| 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(
|
|
@@ -30,7 +29,7 @@ st.markdown("""
|
|
| 30 |
</style>
|
| 31 |
""", unsafe_allow_html=True)
|
| 32 |
|
| 33 |
-
@st.cache_resource(show_spinner="⏳ Загрузка модели LightOnOCR-1B-1025...
|
| 34 |
def load_model():
|
| 35 |
model_name = "lightonai/LightOnOCR-1B-1025"
|
| 36 |
|
|
@@ -61,7 +60,7 @@ def load_image():
|
|
| 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,20 +78,19 @@ if st.button("🔍 Распознать текст", use_container_width=True, t
|
|
| 79 |
if img is None:
|
| 80 |
st.error("Сначала загрузите изображение")
|
| 81 |
else:
|
| 82 |
-
with st.spinner("Распознавание текста... (5–
|
| 83 |
|
| 84 |
-
# Шаблон разговора
|
| 85 |
conversation = [
|
| 86 |
{
|
| 87 |
"role": "user",
|
| 88 |
"content": [
|
| 89 |
{"type": "image"},
|
| 90 |
-
{"type": "text", "text": "Extract
|
| 91 |
]
|
| 92 |
}
|
| 93 |
]
|
| 94 |
|
| 95 |
-
#
|
| 96 |
inputs = processor.apply_chat_template(
|
| 97 |
conversation,
|
| 98 |
add_generation_prompt=True,
|
|
@@ -104,19 +102,16 @@ if st.button("🔍 Распознать текст", use_container_width=True, t
|
|
| 104 |
# Обработка изображения
|
| 105 |
image_inputs = processor.image_processor(img, return_tensors="pt")
|
| 106 |
pixel_values = image_inputs.pixel_values.to(device=device, dtype=dtype)
|
| 107 |
-
|
| 108 |
-
# Получаем размеры изображения (важно для этой модели!)
|
| 109 |
-
height, width = img.height, img.width
|
| 110 |
-
image_sizes = torch.tensor([[height, width]], dtype=torch.long).to(device)
|
| 111 |
|
| 112 |
-
#
|
|
|
|
|
|
|
|
|
|
| 113 |
inputs["pixel_values"] = pixel_values
|
| 114 |
inputs["image_sizes"] = image_sizes
|
| 115 |
|
| 116 |
-
# Перенос
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
for k, v in list(inputs.items()):
|
| 120 |
if isinstance(v, torch.Tensor) and k not in ["pixel_values", "image_sizes"]:
|
| 121 |
inputs[k] = v.to(device=device)
|
| 122 |
|
|
@@ -131,29 +126,35 @@ for k, v in list(inputs.items()):
|
|
| 131 |
eos_token_id=processor.tokenizer.eos_token_id,
|
| 132 |
)
|
| 133 |
|
| 134 |
-
#
|
| 135 |
prompt_length = inputs["input_ids"].shape[1]
|
| 136 |
generated_ids = output_ids[0, prompt_length:]
|
| 137 |
-
|
| 138 |
generated_text = processor.decode(
|
| 139 |
generated_ids,
|
| 140 |
skip_special_tokens=True,
|
| 141 |
clean_up_tokenization_spaces=True
|
| 142 |
).strip()
|
| 143 |
|
| 144 |
-
#
|
| 145 |
-
st.
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 157 |
|
| 158 |
st.markdown("---")
|
| 159 |
st.caption("Сделано на базе [lightonai/LightOnOCR-1B-1025](https://huggingface.co/lightonai/LightOnOCR-1B-1025)")
|
|
|
|
| 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(
|
|
|
|
| 29 |
</style>
|
| 30 |
""", unsafe_allow_html=True)
|
| 31 |
|
| 32 |
+
@st.cache_resource(show_spinner="⏳ Загрузка модели LightOnOCR-1B-1025... (2–6 минут при первом запуске)")
|
| 33 |
def load_model():
|
| 34 |
model_name = "lightonai/LightOnOCR-1B-1025"
|
| 35 |
|
|
|
|
| 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 |
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,
|
|
|
|
| 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 |
|
|
|
|
| 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)
|
| 148 |
+
st.subheader("📝 Распознанный текст")
|
| 149 |
+
st.code(generated_text, language=None)
|
| 150 |
+
st.markdown('</div>', unsafe_allow_html=True)
|
| 151 |
+
|
| 152 |
+
st.download_button(
|
| 153 |
+
label="💾 Скачать как .txt",
|
| 154 |
+
data=generated_text,
|
| 155 |
+
file_name="recognized_text.txt",
|
| 156 |
+
mime="text/plain"
|
| 157 |
+
)
|
| 158 |
|
| 159 |
st.markdown("---")
|
| 160 |
st.caption("Сделано на базе [lightonai/LightOnOCR-1B-1025](https://huggingface.co/lightonai/LightOnOCR-1B-1025)")
|