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

Update Main.py

Browse files
Files changed (1) hide show
  1. Main.py +31 -26
Main.py CHANGED
@@ -81,28 +81,35 @@ if st.button("🔍 Распознать текст", use_container_width=True, t
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()
@@ -119,7 +126,7 @@ if st.button("🔍 Распознать текст", use_container_width=True, t
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
 
@@ -129,21 +136,19 @@ if st.button("🔍 Распознать текст", use_container_width=True, t
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)
137
- st.subheader("📝 Распознанный текст")
138
- st.code(generated_text, language=None)
139
- st.markdown('</div>', unsafe_allow_html=True)
140
-
141
- st.download_button(
142
- label="💾 Скачать как .txt",
143
- data=generated_text,
144
- file_name="recognized_text.txt",
145
- mime="text/plain"
146
- )
147
 
148
  st.markdown("---")
149
  st.caption("Сделано на базе [lightonai/LightOnOCR-1B-1025](https://huggingface.co/lightonai/LightOnOCR-1B-1025)")
 
81
  else:
82
  with st.spinner("Распознавание текста... (5–30 сек на CPU)"):
83
 
84
+ # Промпт для модели
85
+ prompt = "Extract all the text from this image as accurately as possible. Preserve line breaks, formatting and tables."
86
+
87
+ # 1. Получаем текстовый шаблон чата (без токенизации)
88
  conversation = [
89
  {
90
  "role": "user",
91
  "content": [
92
  {"type": "image"},
93
+ {"type": "text", "text": prompt}
94
  ]
95
  }
96
  ]
97
+ text_prompt = processor.apply_chat_template(
 
 
98
  conversation,
99
+ tokenize=False,
100
+ add_generation_prompt=True
101
+ )
102
+
103
+ # 2. Правильный вызов процессора (ключевой момент!)
104
+ inputs = processor(
105
+ text=[text_prompt],
106
+ images=[[img]], # двойной список — обязательно!
107
  return_tensors="pt",
108
+ padding=True,
109
+ size={"longest_edge": 1540} # рекомендуемый размер модели
110
  )
111
 
112
+ # Переносим на устройство
113
  inputs = {
114
  k: (v.to(device=device, dtype=dtype) if v.is_floating_point() else v.to(device))
115
  for k, v in inputs.items()
 
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
 
 
136
  clean_up_tokenization_spaces=True
137
  ).strip()
138
 
139
+ # Результат
140
+ st.success(" Распознавание завершено!")
141
+ st.markdown('<div class="result-box">', unsafe_allow_html=True)
142
+ st.subheader("📝 Распознанный текст")
143
+ st.code(generated_text, language=None)
144
+ st.markdown('</div>', unsafe_allow_html=True)
145
+
146
+ st.download_button(
147
+ label="💾 Скачать как .txt",
148
+ data=generated_text,
149
+ file_name="recognized_text.txt",
150
+ mime="text/plain"
151
+ )
 
 
152
 
153
  st.markdown("---")
154
  st.caption("Сделано на базе [lightonai/LightOnOCR-1B-1025](https://huggingface.co/lightonai/LightOnOCR-1B-1025)")