AlserFurma commited on
Commit
f65dbb9
·
verified ·
1 Parent(s): 22b4c0c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +89 -49
app.py CHANGED
@@ -4,7 +4,7 @@ from PIL import Image
4
  import tempfile
5
  from gradio_client import Client, handle_file
6
  import torch
7
- from transformers import VitsModel, AutoTokenizer, pipeline
8
  import scipy.io.wavfile as wavfile
9
  import traceback
10
  import base64
@@ -26,10 +26,10 @@ try:
26
  translator = pipeline("translation", model="facebook/nllb-200-distilled-600M", device=device)
27
  print("Модель перевода (NLLB) загружена успешно!")
28
 
29
- # Модель для генерации вопросов (с use_fast=False для избежания ошибки)
30
- qg_tokenizer = AutoTokenizer.from_pretrained("iarfmoose/t5-base-question-generator", use_fast=False)
31
- print("QG tokenizer загружен (slow mode)!")
32
- qg_pipeline = pipeline("text2text-generation", model="iarfmoose/t5-base-question-generator", tokenizer=qg_tokenizer, device=device)
33
  print("Модель генерации вопросов загружена!")
34
 
35
  # Модель для QA (извлечение ответов)
@@ -103,8 +103,6 @@ def inference(image: Image.Image, text: str):
103
  print(f"Подключение к {TALKING_HEAD_SPACE}...")
104
  client = Client(TALKING_HEAD_SPACE)
105
 
106
- print("Доступные API методы:", client.view_api())
107
-
108
  result = client.predict(
109
  image_path=handle_file(img_path),
110
  audio_path=handle_file(audio_path),
@@ -132,7 +130,7 @@ def inference(image: Image.Image, text: str):
132
  raise ValueError("Видео не сгенерировано! Проверьте API.")
133
 
134
  print(f"Видео сгенерировано: {video_path}")
135
- error_msg = "✅ Бейне сәтті жасалды! "
136
 
137
  except Exception as e:
138
  error_msg = f"❌ Ошибка: {str(e)}"
@@ -152,7 +150,7 @@ def inference(image: Image.Image, text: str):
152
 
153
  def generate_interactive_lesson(text, video_path):
154
  try:
155
- # Перевод текста на английский для QG и QA (модели на en)
156
  english_text = translator(text, src_lang="rus_Cyrl", tgt_lang="eng_Latn")[0]['translation_text']
157
  print(f"English text: {english_text[:50]}...")
158
 
@@ -161,17 +159,22 @@ def generate_interactive_lesson(text, video_path):
161
  questions = []
162
 
163
  for sent in sentences:
164
- # Генерация вопроса (формат для модели)
165
- qg_input = f"<answer> {sent} <context> {english_text}"
166
- generated = qg_pipeline(qg_input)[0]['generated_text']
167
- question_en = generated.split("question: ")[-1].strip() if "question: " in generated else generated
 
 
 
 
 
168
 
169
  # Извлечение правильного ответа
170
  qa_result = qa_pipeline(question=question_en, context=english_text)
171
  correct_answer_en = qa_result['answer']
172
 
173
- # Неправильный ответ (placeholder)
174
- wrong_answer_en = "Incorrect option"
175
 
176
  # Перевод на казахский
177
  question = translator(question_en, src_lang="eng_Latn", tgt_lang="kaz_Cyrl")[0]['translation_text']
@@ -189,25 +192,41 @@ def generate_interactive_lesson(text, video_path):
189
  video_base64 = base64.b64encode(f.read()).decode('utf-8')
190
 
191
  # Строим HTML урока
192
- html = """
193
  <html>
194
- <head><title>Интерактивный урок</title></head>
 
 
 
 
 
 
 
 
 
 
 
 
195
  <body>
196
- <h1>Интерактивный урок</h1>
197
- <video controls width="600">
198
  <source src="data:video/mp4;base64,{}" type="video/mp4">
199
  </video>
200
- <p>Текст лекции: {}</p>
 
201
  """.format(video_base64, text.replace("\n", "<br>"))
202
 
203
  for i, q in enumerate(questions):
 
204
  html += f"""
205
- <div>
206
- <p>Сұрақ {i+1}: {q['question']}</p>
207
- <input type="radio" name="q{i}" value="correct" id="correct{i}"> <label for="correct{i}">{q['correct']}</label><br>
208
- <input type="radio" name="q{i}" value="wrong" id="wrong{i}"> <label for="wrong{i}">{q['wrong']}</label><br>
209
- <button onclick="checkAnswer({i}, '{q['correct']}')">Тексеру</button>
210
- <p id="feedback{i}"></p>
 
 
211
  </div>
212
  """
213
 
@@ -218,14 +237,15 @@ def generate_interactive_lesson(text, video_path):
218
  var feedback = document.getElementById('feedback' + i);
219
  if (selected) {
220
  if (selected.value === 'correct') {
221
- feedback.innerHTML = 'Дұрыс!';
222
  feedback.style.color = 'green';
223
  } else {
224
- feedback.innerHTML = 'Қате. Дұрыс жауап: ' + correct;
225
  feedback.style.color = 'red';
226
  }
227
  } else {
228
- feedback.innerHTML = 'Жауапты таңдаңыз!';
 
229
  }
230
  }
231
  </script>
@@ -233,44 +253,64 @@ def generate_interactive_lesson(text, video_path):
233
  </html>
234
  """
235
 
236
- # Экранируем специальные символы вне f-строки
237
- escaped_html = html.replace('`', r'\`').replace('$', r'\$')
238
 
239
- # HTML для кнопки открытия в новой вкладке
240
  open_button_html = f"""
241
- <button onclick="var w = window.open(); w.document.write(`{escaped_html}`);">Интерактивті сабақты жаңа қойындыда ашу</button>
 
 
 
 
 
 
 
 
 
 
 
242
  """
243
 
244
  return open_button_html
245
 
246
  except Exception as e:
247
- return f"Қате: {str(e)}"
 
248
 
249
  # Интерфейс Gradio
250
- title = "Бейне Оқытушы"
251
  description = """Суретіңізді жүктеп, дәріс мәтінін орыс тілінде енгізіңіз.
252
  Жасанды интеллект мәтінді қазақ тіліне аударады және сіздің қатысуыңызбен бейне дәріс жасайды!
 
253
  **Талаптар:**
254
- - Фото: бет анық көрінетін, алдыңғы жағынан түсірілген сурет
255
- - Мәтін: орыс тілінде, ең көбі 500 таңба"""
256
 
257
- with gr.Blocks() as iface:
258
  gr.Markdown(f"# {title}\n{description}")
259
 
260
- image_input = gr.Image(type="pil", label="📸 Фото дәріскер")
261
- text_input = gr.Textbox(lines=5, placeholder="Дәріс мәтінін орыс тілінде енгізіңіз (500 таңбаға дейін)...", label="📝Дәріс мәтіні (орыс тілінде)")
262
-
263
- generate_video_btn = gr.Button("Бейнені генерациялау")
264
-
265
- video_output = gr.Video(label="🎬 Дайын бейне (қазақ тілінде)")
266
- status = gr.Textbox(label="ℹ️Мәртебесі", interactive=False)
267
-
268
- interactive_btn = gr.Button("Интерактивті сабақты жасау", visible=False)
 
 
 
 
269
 
 
270
  lesson_output = gr.HTML(label="Интерактивті сабақ", visible=False)
271
 
272
- def show_interactive_btn(video, status):
273
- return gr.update(visible=True)
 
 
274
 
275
  generate_video_btn.click(
276
  inference,
 
4
  import tempfile
5
  from gradio_client import Client, handle_file
6
  import torch
7
+ from transformers import VitsModel, AutoTokenizer, pipeline, T5Tokenizer, T5ForConditionalGeneration
8
  import scipy.io.wavfile as wavfile
9
  import traceback
10
  import base64
 
26
  translator = pipeline("translation", model="facebook/nllb-200-distilled-600M", device=device)
27
  print("Модель перевода (NLLB) загружена успешно!")
28
 
29
+ # Модель для генерации вопросов (явно используем T5Tokenizer - slow tokenizer)
30
+ print("Загрузка QG модели...")
31
+ qg_tokenizer = T5Tokenizer.from_pretrained("iarfmoose/t5-base-question-generator", legacy=False)
32
+ qg_model = T5ForConditionalGeneration.from_pretrained("iarfmoose/t5-base-question-generator").to(device)
33
  print("Модель генерации вопросов загружена!")
34
 
35
  # Модель для QA (извлечение ответов)
 
103
  print(f"Подключение к {TALKING_HEAD_SPACE}...")
104
  client = Client(TALKING_HEAD_SPACE)
105
 
 
 
106
  result = client.predict(
107
  image_path=handle_file(img_path),
108
  audio_path=handle_file(audio_path),
 
130
  raise ValueError("Видео не сгенерировано! Проверьте API.")
131
 
132
  print(f"Видео сгенерировано: {video_path}")
133
+ error_msg = "✅ Бейне сәтті жасалды!"
134
 
135
  except Exception as e:
136
  error_msg = f"❌ Ошибка: {str(e)}"
 
150
 
151
  def generate_interactive_lesson(text, video_path):
152
  try:
153
+ # Перевод текста на английский для QG и QA
154
  english_text = translator(text, src_lang="rus_Cyrl", tgt_lang="eng_Latn")[0]['translation_text']
155
  print(f"English text: {english_text[:50]}...")
156
 
 
159
  questions = []
160
 
161
  for sent in sentences:
162
+ # Генерация вопроса
163
+ qg_input = f"generate question: {sent}"
164
+ input_ids = qg_tokenizer.encode(qg_input, return_tensors="pt").to(device)
165
+
166
+ with torch.no_grad():
167
+ outputs = qg_model.generate(input_ids, max_length=64)
168
+
169
+ question_en = qg_tokenizer.decode(outputs[0], skip_special_tokens=True)
170
+ print(f"Generated question: {question_en}")
171
 
172
  # Извлечение правильного ответа
173
  qa_result = qa_pipeline(question=question_en, context=english_text)
174
  correct_answer_en = qa_result['answer']
175
 
176
+ # Неправильный ответ (простой пример)
177
+ wrong_answer_en = "Not mentioned in the text"
178
 
179
  # Перевод на казахский
180
  question = translator(question_en, src_lang="eng_Latn", tgt_lang="kaz_Cyrl")[0]['translation_text']
 
192
  video_base64 = base64.b64encode(f.read()).decode('utf-8')
193
 
194
  # Строим HTML урока
195
+ html = """<!DOCTYPE html>
196
  <html>
197
+ <head>
198
+ <meta charset="UTF-8">
199
+ <title>Интерактивный урок</title>
200
+ <style>
201
+ body { font-family: Arial, sans-serif; max-width: 800px; margin: 20px auto; padding: 20px; }
202
+ h1 { color: #333; }
203
+ video { margin: 20px 0; }
204
+ .question { background: #f5f5f5; padding: 15px; margin: 20px 0; border-radius: 5px; }
205
+ button { background: #4CAF50; color: white; padding: 10px 20px; border: none; border-radius: 4px; cursor: pointer; }
206
+ button:hover { background: #45a049; }
207
+ .feedback { margin-top: 10px; font-weight: bold; }
208
+ </style>
209
+ </head>
210
  <body>
211
+ <h1>Интерактивті сабақ</h1>
212
+ <video controls width="100%">
213
  <source src="data:video/mp4;base64,{}" type="video/mp4">
214
  </video>
215
+ <p><strong>Дәріс мәтіні:</strong> {}</p>
216
+ <h2>Тесттер:</h2>
217
  """.format(video_base64, text.replace("\n", "<br>"))
218
 
219
  for i, q in enumerate(questions):
220
+ correct_escaped = q['correct'].replace("'", "\\'")
221
  html += f"""
222
+ <div class="question">
223
+ <p><strong>Сұрақ {i+1}:</strong> {q['question']}</p>
224
+ <input type="radio" name="q{i}" value="correct" id="correct{i}">
225
+ <label for="correct{i}">{q['correct']}</label><br>
226
+ <input type="radio" name="q{i}" value="wrong" id="wrong{i}">
227
+ <label for="wrong{i}">{q['wrong']}</label><br><br>
228
+ <button onclick="checkAnswer({i}, '{correct_escaped}')">Тексеру</button>
229
+ <p class="feedback" id="feedback{i}"></p>
230
  </div>
231
  """
232
 
 
237
  var feedback = document.getElementById('feedback' + i);
238
  if (selected) {
239
  if (selected.value === 'correct') {
240
+ feedback.innerHTML = '✅ Дұрыс!';
241
  feedback.style.color = 'green';
242
  } else {
243
+ feedback.innerHTML = '❌ Қате. Дұрыс жауап: ' + correct;
244
  feedback.style.color = 'red';
245
  }
246
  } else {
247
+ feedback.innerHTML = '⚠️ Жауапты таңдаңыз!';
248
+ feedback.style.color = 'orange';
249
  }
250
  }
251
  </script>
 
253
  </html>
254
  """
255
 
256
+ # Экранируем для JavaScript
257
+ escaped_html = html.replace('\\', '\\\\').replace('`', '\\`').replace('$', '\\$')
258
 
259
+ # Кнопка для открытия в новой вкладке
260
  open_button_html = f"""
261
+ <div style="text-align: center; padding: 20px;">
262
+ <button onclick="openLesson()" style="background: #2196F3; color: white; padding: 15px 30px; font-size: 16px; border: none; border-radius: 5px; cursor: pointer;">
263
+ 📚 Интерактивті сабақты жаңа қойындыда ашу
264
+ </button>
265
+ </div>
266
+ <script>
267
+ function openLesson() {{
268
+ var w = window.open();
269
+ w.document.write(`{escaped_html}`);
270
+ w.document.close();
271
+ }}
272
+ </script>
273
  """
274
 
275
  return open_button_html
276
 
277
  except Exception as e:
278
+ traceback.print_exc()
279
+ return f"<p style='color: red;'>❌ Қате: {str(e)}</p>"
280
 
281
  # Интерфейс Gradio
282
+ title = "🎓 Бейне Оқытушы"
283
  description = """Суретіңізді жүктеп, дәріс мәтінін орыс тілінде енгізіңіз.
284
  Жасанды интеллект мәтінді қазақ тіліне аударады және сіздің қатысуыңызбен бейне дәріс жасайды!
285
+
286
  **Талаптар:**
287
+ - 📸 Фото: бет анық көрінетін, алдыңғы жағынан түсірілген сурет
288
+ - 📝 Мәтін: орыс тілінде, ең көбі 500 таңба"""
289
 
290
+ with gr.Blocks(theme=gr.themes.Soft()) as iface:
291
  gr.Markdown(f"# {title}\n{description}")
292
 
293
+ with gr.Row():
294
+ with gr.Column():
295
+ image_input = gr.Image(type="pil", label="📸 Фото дәріскер")
296
+ text_input = gr.Textbox(
297
+ lines=5,
298
+ placeholder="Мысалы: Сәлеметсіздер ме! Бүгін біз математика туралы сөйлесеміз...",
299
+ label="📝 Дәріс мәтіні (орыс тілінде, 500 таңбаға дейін)"
300
+ )
301
+ generate_video_btn = gr.Button("🎬 Бейнені генерациялау", variant="primary")
302
+
303
+ with gr.Column():
304
+ video_output = gr.Video(label="🎬 Дайын бейне (қазақ тілінде)")
305
+ status = gr.Textbox(label="ℹ️ Мәртебесі", interactive=False)
306
 
307
+ interactive_btn = gr.Button("📚 Интерактивті сабақты жасау", visible=False, variant="secondary")
308
  lesson_output = gr.HTML(label="Интерактивті сабақ", visible=False)
309
 
310
+ def show_interactive_btn(video, status_msg):
311
+ if video and "✅" in status_msg:
312
+ return gr.update(visible=True)
313
+ return gr.update(visible=False)
314
 
315
  generate_video_btn.click(
316
  inference,