Spaces:
Build error

Surficata commited on
Commit
b2acdfd
·
verified ·
1 Parent(s): 75fb180

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -141
app.py CHANGED
@@ -22,8 +22,6 @@ if OPENAI_API_KEY:
22
  else: print("Warning: OPENAI_API_KEY not set.")
23
 
24
  # --- Helper Functions ---
25
- # (format_timestamp, format_yt_timestamp, parse_chapters, format_transcript_with_chapters)
26
- # (format_srt, format_vtt, call_gpt - remain the same)
27
  def format_timestamp(seconds, format_type='srt', precision='milliseconds'):
28
  if not isinstance(seconds, (int, float)) or seconds < 0: seconds = 0
29
  seconds_int = int(seconds); milliseconds_part = seconds - seconds_int; milliseconds = int(milliseconds_part * 1000)
@@ -31,16 +29,18 @@ def format_timestamp(seconds, format_type='srt', precision='milliseconds'):
31
  hours, remainder = divmod(total_seconds, 3600); minutes, seconds_rem = divmod(remainder, 60)
32
  if precision == 'seconds': return f"{hours:02}:{minutes:02}:{seconds_rem:02}"
33
  else: separator = ',' if format_type == 'srt' else '.'; return f"{hours:02}:{minutes:02}:{seconds_rem:02}{separator}{milliseconds:03}"
 
34
  def format_yt_timestamp(seconds):
35
  if not isinstance(seconds, (int, float)) or seconds < 0: seconds = 0
36
  td = datetime.timedelta(seconds=int(seconds)); total_seconds = int(td.total_seconds())
37
  hours, remainder = divmod(total_seconds, 3600); minutes, seconds_rem = divmod(remainder, 60)
38
  if hours > 0: return f"{hours}:{minutes:02}:{seconds_rem:02}"
39
  else: return f"{minutes:02}:{seconds_rem:02}"
 
40
  def parse_chapters(chapter_text):
41
  chapters = []; pattern = re.compile(r"^(?:(\d{1,2}):)?(\d{1,2}):(\d{2})\s*-\s*(.+)$", re.MULTILINE)
42
  if not chapter_text: return chapters
43
- print(f"Attempting to parse chapter text:\n---\n{chapter_text}\n---")
44
  for match in pattern.finditer(chapter_text):
45
  try:
46
  hours_str = match.group(1); minutes_str = match.group(2); seconds_str = match.group(3); title = match.group(4).strip()
@@ -53,23 +53,42 @@ def parse_chapters(chapter_text):
53
  except Exception as e: print(f"Error sorting chapters: {e}")
54
  print(f"Parsed chapters: {chapters}")
55
  return chapters
 
 
56
  def format_transcript_with_chapters(edited_transcript, parsed_chapters):
57
  if not parsed_chapters or not edited_transcript: return edited_transcript
58
- output_parts = []; last_char_pos = 0; total_len = len(edited_transcript); audio_duration_estimate = parsed_chapters[-1]['time'] + 60 if parsed_chapters else 3600
 
59
  print("Formatting transcript with chapters...")
60
  for i, chapter in enumerate(parsed_chapters):
61
  approx_char_pos = int((chapter['time'] / audio_duration_estimate) * total_len) if audio_duration_estimate > 0 else 0
62
  insert_pos = edited_transcript.rfind('\n', last_char_pos, max(last_char_pos + 1, approx_char_pos))
 
 
63
  if insert_pos == -1 or insert_pos < last_char_pos:
64
  if i == 0: insert_pos = 0
65
- else: insert_pos = max(last_char_pos + 1, approx_char_pos); nearby_newline = edited_transcript.rfind('\n', max(0, insert_pos - 100), insert_pos)
66
- if nearby_newline > last_char_pos: insert_pos = nearby_newline + 1
67
- else: insert_pos += 1
68
- insert_pos = min(max(last_char_pos, insert_pos), total_len); output_parts.append(edited_transcript[last_char_pos:insert_pos])
69
- heading = f"\n\n({format_timestamp(chapter['time'], precision='seconds')} - {chapter['title']})\n"; output_parts.append(heading); last_char_pos = insert_pos
70
- output_parts.append(edited_transcript[last_char_pos:]); result = "".join(output_parts).strip()
 
 
 
 
 
 
 
 
 
 
 
 
71
  print("Transcript formatting complete.")
72
  return result
 
 
73
  def format_srt(segments):
74
  srt_content = ""
75
  if not segments: return ""
@@ -106,29 +125,20 @@ def call_gpt(prompt, system_message="Jsi užitečný AI asistent."):
106
  result = response.choices[0].message.content.strip(); print("GPT OK."); return result
107
  except Exception as e: print(f"GPT Error: {e}"); traceback.print_exc(); return f"Chyba GPT: {e}"
108
  def generate_article_content(transcript_state, context_state, article_extra_prompt, progress=gr.Progress(track_tqdm=True)):
109
- # Added try-except block for robustness
110
  article_result = "Chyba: Generování článku selhalo."
111
  try:
112
  print("--- generate_article_content called ---")
113
  if not transcript_state or transcript_state.startswith("Chyba:"): return "Chyba: Nelze generovat článek, chybí platný přepis."
114
  if not client: return "Chyba: OpenAI klient není inicializován."
115
-
116
  progress(0.1, desc="Generování článku..."); print("Generating article...")
117
  word_count = len(str(transcript_state).split()); is_long_article = word_count > 400
118
- # --- FULL ARTICLE PROMPT --- (Ensure it's the correct one)
119
  article_prompt = f"""Jsi zkušený AI redaktor... (plný prompt viz dříve)"""
120
  system_msg = "Jsi špičkový AI redaktor píšící česky..."
121
  progress(0.5, desc="Volání GPT..."); article_result = call_gpt(article_prompt, system_message=system_msg)
122
  progress(1.0, desc="Článek hotov."); print("Article generation OK.")
123
- # Handle potential GPT error message
124
- if article_result.startswith("Chyba GPT:"):
125
- print(f"Article generation failed with GPT error: {article_result}")
126
- # Keep the error message to display in UI
127
- except Exception as e:
128
- error_message = f"Chyba při generování článku: {e}"
129
- print(error_message); traceback.print_exc(); article_result = error_message
130
  print(f"--- generate_article_content finished, returning: {str(article_result)[:100]}...")
131
- return article_result # Return result or error message
132
  def generate_srt_file(segments_state):
133
  if not segments_state: gr.Warning("Nelze generovat titulky..."); return None, None
134
  print("Generating SRT file..."); srt_content = format_srt(segments_state)
@@ -146,9 +156,7 @@ def generate_vtt_file(segments_state):
146
  print(f"VTT file generated: {vtt_filepath}"); return vtt_filepath, vtt_filepath
147
  except Exception as e: print(f"Error writing VTT file: {e}"); traceback.print_exc(); gr.Error(f"Chyba zápisu VTT: {e}"); return None, None
148
  def create_download_zip(transcript, chapters, reels, srt_path, vtt_path, article):
149
- # (Function remains the same)
150
  print("Creating ZIP file..."); zip_error = None; zip_path = None; base_filename = "prepisovac_vystupy"
151
- # ...(Rest of the zip function remains the same)...
152
  if article and not article.startswith("Chyba:"):
153
  title_match = re.search(r"Popisný:\s*\n(.+)", article);
154
  if title_match: extracted_title = title_match.group(1).strip(); sanitized_title = re.sub(r'[\\/*?:"<>|]', "", extracted_title).replace(" ", "_")[:50]
@@ -171,163 +179,73 @@ def create_download_zip(transcript, chapters, reels, srt_path, vtt_path, article
171
  shutil.copyfile(zip_filepath, final_zip_path); zip_path = final_zip_path; print(f"ZIP created: {zip_path}")
172
  except Exception as e: zip_error = f"Chyba ZIP: {e}"; print(zip_error); traceback.print_exc(); return None
173
  return zip_path
174
-
175
- # --- Main Processing Function ---
176
  def process_audio(audio_filepath, description, keywords, progress=gr.Progress(track_tqdm=True)):
177
- # Initialize variables with clearer initial/error messages
178
- formatted_transcript_w_chapters = "Probíhá zpracování..."
179
- chapters_formatted = "" # Start empty, fill on success
180
- reels_suggestions = "" # Start empty, fill on success
181
- edited_transcript_for_state = ""
182
- context_for_state = ""
183
- segments = []
184
-
185
  try:
186
- # 1. Transcription
187
- progress(0.1, desc="Přepis audia..."); print(f"Transcribing: {audio_filepath}")
188
  if not audio_filepath: raise ValueError("Chybí audio soubor.")
189
- with open(audio_filepath, "rb") as f: transcription_response = client.audio.transcriptions.create(
190
- model=WHISPER_MODEL, file=f, response_format="verbose_json", language=None, timestamp_granularities=["segment"] )
191
  if not (transcription_response and hasattr(transcription_response, 'text')): raise Exception(f"Přepis selhal: {transcription_response}")
192
  raw_transcript = transcription_response.text or ""; detected_language = getattr(transcription_response, 'language', 'N/A')
193
  print(f"Transcription OK. Lang: {detected_language}");
194
  if hasattr(transcription_response, 'segments') and transcription_response.segments:
195
- segments = transcription_response.segments
196
- audio_duration = segments[-1].end if segments else 0
197
- print(f"{len(segments)} segments. Duration: {audio_duration:.2f}s")
198
- progress(0.2, desc="Přepis dokončen.") # Corrected progress step
199
-
200
- # 2. Prepare Context
201
  context_parts = [];
202
  if description: context_parts.append(f"Popis: {description}")
203
  if keywords: context_parts.append(f"Klíčová slova: {keywords}")
204
  context_for_state = "\n".join(context_parts) if context_parts else "Žádný kontext."
205
-
206
- # 3. Edit Transcript to Czech
207
- progress(0.3, desc="Úprava textu (GPT)..."); print("Editing to CZ...") # Corrected progress step
208
- # --- UPDATED EDIT PROMPT ---
209
- edit_prompt = f"""Jsi profesionální editor českého jazyka. Tvým úkolem je vzít následující automatický přepis (může obsahovat více jazyků) a upravit ho do podoby perfektního, čtivého a gramaticky správného redakčního textu VŽDY V ČEŠTINĚ.
210
-
211
- Pravidla úprav:
212
- - Výsledný text MUSÍ být kompletně v ČEŠTINĚ. Pokud narazíš na pasáže v jiném jazyce (např. angličtina, slovenština), přelož je plynule do češtiny a začleň je do textu.
213
- - NUANCE: Běžně používané anglicismy, cizí slova nebo slangové výrazy, které jsou přirozenou součástí mluvené češtiny (např. 'feedback', 'cool', 'deadline', 'meeting', 'sorry jako', 'by default'), NEPŘEKLÁDEJ otrocky, pokud zapadají do kontextu české věty. Pouze je gramaticky a stylisticky začleň. Cílem je přirozeně znějící český text, ne puristický překlad.
214
- - Oprav veškeré gramatické chyby, překlepy a interpunkci v češtině.
215
- - Odstraň slovní vatu, hezitace (ehm, hmm), opakující se slova, nedokončené věty (pokud nemají význam).
216
- - Vytvoř logické odstavce.
217
- - Použij kontext a klíčová slova pro opravu/správné psaní specifických termínů a jmen.
218
- - Zachovej původní smysl a informace. Neměň fakta.
219
- - Nyní napiš POUZE výsledný upravený text bez jakýchkoli dalších komentářů nebo úvodních frází.
220
-
221
- Poskytnutý kontext:
222
- {context_for_state}
223
- Původní přepis k úpravě (detekovaný jazyk: {detected_language}):
224
- ---
225
- {raw_transcript}
226
- ---"""
227
- edited_transcript_for_state = call_gpt(edit_prompt, system_message="Jsi špičkový editor se specializací na převod mluvené řeči do perfektní psané češtiny.")
228
  if edited_transcript_for_state.startswith("Chyba:"): raise Exception(f"Chyba editace GPT: {edited_transcript_for_state}")
229
  print("Editing OK.")
230
- # Initialize display transcript here, may be overwritten later if chapters work
231
- formatted_transcript_w_chapters = edited_transcript_for_state
232
- progress(0.5, desc="Generování kapitol (GPT)...") # Corrected progress step
233
-
234
- # 4. Generate Chapters (in Czech)
235
- parsed_chapters_list = []
236
- chapters_formatted = "Nelze generovat (chybí segmenty)." # Default if no segments
237
  if segments:
238
- chapters_formatted = "Nepodařilo se vygenerovat kapitoly." # Default if segments exist but fail
239
  print("Generating chapters...");
240
- if audio_duration < 60: num_chapters = 1 # Special case for very short audio
241
  elif audio_duration < 600: num_chapters = 3
242
  elif audio_duration < 1800: num_chapters = random.randint(5, 7)
243
  else: num_chapters = random.randint(7, 10)
244
- print(f"Requesting {num_chapters} chapters...")
245
  try:
246
- # --- UPDATED CHAPTER PROMPT ---
247
- chapter_prompt = f"""Jsi AI pro YouTube kapitoly. Analyzuj následující text v ČEŠTINĚ a vygeneruj přibližně {num_chapters} kapitol (může být méně, pokud text není dostatečně členitý, ale alespoň 1, pokud text dává smysl).
248
- Kontext:
249
- {context_for_state}
250
- Text k analýze (ČEŠTINA):
251
- ---
252
- {edited_transcript_for_state[:6000]}
253
- ---
254
- Instrukce: Identifikuj hlavní témata. Urči čas začátku HH:MM:SS pro každé téma (z původního audia). Název v ČEŠTINĚ (max 5-7 slov). Formát PŘESNĚ: HH:MM:SS - Název. Seřadit. Pokud nenajdeš žádné smysluplné kapitoly, vrať text "ŽÁDNÉ KAPITOLY". Jinak vrať POUZE seznam kapitol, každá na novém řádku."""
255
- chapters_raw = call_gpt(chapter_prompt, system_message="Jsi AI expert na YT kapitoly v češtině, dodržující formát.")
256
  print(f"Raw Chapters Output from GPT:\n---\n{chapters_raw}\n---")
257
  if not chapters_raw.startswith("Chyba:") and "ŽÁDNÉ KAPITOLY" not in chapters_raw:
258
- parsed_chapters_list = parse_chapters(chapters_raw)
259
  if parsed_chapters_list:
260
  chapters_formatted_list = [f"{format_yt_timestamp(ch['time'])} - {ch['title']}" for ch in parsed_chapters_list]
261
  chapters_formatted = "\n".join(chapters_formatted_list); print("Chapters OK.")
262
  else: chapters_formatted = "Nepodařilo se rozpoznat formát kapitol."; print("Chapter parsing failed.")
263
- elif "ŽÁDNÉ KAPITOLY" in chapters_raw:
264
- chapters_formatted = "Pro tento text nebyly nalezeny žádné smysluplné kapitoly."
265
- print("GPT indicated no chapters found.")
266
- else: chapters_formatted = chapters_raw # Keep the error message from call_gpt
267
- print(f"Chapter gen message: {chapters_formatted}")
268
  except Exception as e: chapters_formatted = f"Chyba kapitol: {e}"; print(chapters_formatted); traceback.print_exc()
269
- else: print("Skipping chapters (no segments).")
270
- progress(0.7, desc="Generování Reels (GPT)...") # Corrected progress step
271
-
272
- # 5. Generate Reels Suggestions (in Czech)
273
- reels_suggestions = "Nelze generovat (chybí text)." # Default if transcript fails
274
  if edited_transcript_for_state and not edited_transcript_for_state.startswith("Chyba:"):
275
- reels_suggestions = "Nepodařilo se vygenerovat návrhy pro Reels." # Default if GPT fails
276
  print("Generating Reels suggestions...")
277
  try:
278
- # --- UPDATED REELS PROMPT ---
279
- reels_prompt = f"""Jsi AI specialista na sociální média. Analyzuj následující text v ČEŠTINĚ a identifikuj 3-5 krátkých (15-45 sekund), velmi zajímavých úseků pro Reels/TikTok. Hledej silné výroky, emoce, klíčové momenty.
280
-
281
- Kontext:
282
- {context_for_state}
283
- Text k analýze (ČEŠTINA):
284
- ---
285
- {edited_transcript_for_state}
286
- ---
287
- Instrukce: Pro každý návrh uveď:
288
- - Přesný čas začátku a konce úseku HH:MM:SS.ms - HH:MM:SS.ms (z původního audia).
289
- - Stručný popis obsahu (1-2 věty v ČEŠTINĚ).
290
- - Krátkou citaci/frázi z úseku (v ČEŠTINĚ).
291
-
292
- Formátuj výstup PŘESNĚ takto (každý návrh oddělený prázdným řádkem), NEPIŠ nic jiného:
293
-
294
- Čas: HH:MM:SS.ms - HH:MM:SS.ms
295
- Popis: [Stručný popis]
296
- Citace: „[Citace]“
297
-
298
- Čas: HH:MM:SS.ms - HH:MM:SS.ms
299
- Popis: [Stručný popis]
300
- Citace: „[Citace]“
301
- ... (celkem 3-5 návrhů)"""
302
- reels_result = call_gpt(reels_prompt, system_message="Jsi AI expert na tvorbu návrhů pro Reels v češtině.")
303
  if not reels_result.startswith("Chyba:") and "Čas:" in reels_result and "Popis:" in reels_result:
304
  reels_suggestions = reels_result; print("Reels OK.")
305
  else: print(f"Reels output unexpected or error: {reels_result[:200]}...")
306
  except Exception as e: reels_suggestions = f"Chyba Reels: {e}"; print(reels_suggestions); traceback.print_exc()
307
- progress(0.9, desc="Formátování výstupu...") # Corrected progress step
308
-
309
- # 6. Format Transcript with Chapters (only if chapters were successfully parsed)
310
- if parsed_chapters_list:
311
- formatted_transcript_w_chapters = format_transcript_with_chapters(edited_transcript_for_state, parsed_chapters_list)
312
- else:
313
- formatted_transcript_w_chapters = edited_transcript_for_state # Show clean transcript if chapters failed
314
-
315
  progress(1.0, desc="Hotovo!"); print("Processing OK.")
316
- # Return results for UI and state data
317
- return (
318
- formatted_transcript_w_chapters, chapters_formatted, reels_suggestions,
319
- edited_transcript_for_state, context_for_state, segments,
320
- chapters_formatted, reels_suggestions
321
- )
322
-
323
  except Exception as e:
324
  error_message = f"Chyba během zpracování: {e}"; print(error_message); traceback.print_exc()
325
- # Return error message for the first UI component and defaults/empty for others
326
  return error_message, "", "", "", "", [], "", ""
327
 
328
-
329
  # --- Gradio Interface Definition ---
330
- theme = gr.themes.Default() # Using Default theme
331
 
332
  # --- Build Gradio UI ---
333
  with gr.Blocks(theme=theme) as demo:
@@ -369,6 +287,7 @@ with gr.Blocks(theme=theme) as demo:
369
  download_file_output = gr.File(label="Stažený ZIP", interactive=False, visible=False)
370
 
371
  # --- Event Handling ---
 
372
  submit_button.click(
373
  fn=process_audio, inputs=[audio_input, description_input, keywords_input],
374
  outputs=[ edited_output_formatted, chapters_output, reels_output, transcript_state, context_state, segments_state, chapters_state, reels_state ] )
 
22
  else: print("Warning: OPENAI_API_KEY not set.")
23
 
24
  # --- Helper Functions ---
 
 
25
  def format_timestamp(seconds, format_type='srt', precision='milliseconds'):
26
  if not isinstance(seconds, (int, float)) or seconds < 0: seconds = 0
27
  seconds_int = int(seconds); milliseconds_part = seconds - seconds_int; milliseconds = int(milliseconds_part * 1000)
 
29
  hours, remainder = divmod(total_seconds, 3600); minutes, seconds_rem = divmod(remainder, 60)
30
  if precision == 'seconds': return f"{hours:02}:{minutes:02}:{seconds_rem:02}"
31
  else: separator = ',' if format_type == 'srt' else '.'; return f"{hours:02}:{minutes:02}:{seconds_rem:02}{separator}{milliseconds:03}"
32
+
33
  def format_yt_timestamp(seconds):
34
  if not isinstance(seconds, (int, float)) or seconds < 0: seconds = 0
35
  td = datetime.timedelta(seconds=int(seconds)); total_seconds = int(td.total_seconds())
36
  hours, remainder = divmod(total_seconds, 3600); minutes, seconds_rem = divmod(remainder, 60)
37
  if hours > 0: return f"{hours}:{minutes:02}:{seconds_rem:02}"
38
  else: return f"{minutes:02}:{seconds_rem:02}"
39
+
40
  def parse_chapters(chapter_text):
41
  chapters = []; pattern = re.compile(r"^(?:(\d{1,2}):)?(\d{1,2}):(\d{2})\s*-\s*(.+)$", re.MULTILINE)
42
  if not chapter_text: return chapters
43
+ print(f"Parsing chapter text:\n---\n{chapter_text}\n---")
44
  for match in pattern.finditer(chapter_text):
45
  try:
46
  hours_str = match.group(1); minutes_str = match.group(2); seconds_str = match.group(3); title = match.group(4).strip()
 
53
  except Exception as e: print(f"Error sorting chapters: {e}")
54
  print(f"Parsed chapters: {chapters}")
55
  return chapters
56
+
57
+ # --- CORRECTED format_transcript_with_chapters ---
58
  def format_transcript_with_chapters(edited_transcript, parsed_chapters):
59
  if not parsed_chapters or not edited_transcript: return edited_transcript
60
+ output_parts = []; last_char_pos = 0; total_len = len(edited_transcript)
61
+ audio_duration_estimate = parsed_chapters[-1]['time'] + 60 if parsed_chapters else 3600
62
  print("Formatting transcript with chapters...")
63
  for i, chapter in enumerate(parsed_chapters):
64
  approx_char_pos = int((chapter['time'] / audio_duration_estimate) * total_len) if audio_duration_estimate > 0 else 0
65
  insert_pos = edited_transcript.rfind('\n', last_char_pos, max(last_char_pos + 1, approx_char_pos))
66
+ nearby_newline = -1 # Initialize nearby_newline here, before the if/else block
67
+
68
  if insert_pos == -1 or insert_pos < last_char_pos:
69
  if i == 0: insert_pos = 0
70
+ else:
71
+ insert_pos = max(last_char_pos + 1, approx_char_pos)
72
+ # Assign nearby_newline
73
+ nearby_newline = edited_transcript.rfind('\n', max(0, insert_pos - 100), insert_pos)
74
+ # Use nearby_newline (it's now guaranteed to be assigned, at least -1)
75
+ if nearby_newline > last_char_pos:
76
+ insert_pos = nearby_newline + 1
77
+ else:
78
+ insert_pos += 1
79
+
80
+ insert_pos = min(max(last_char_pos, insert_pos), total_len);
81
+ output_parts.append(edited_transcript[last_char_pos:insert_pos])
82
+ heading = f"\n\n({format_timestamp(chapter['time'], precision='seconds')} - {chapter['title']})\n";
83
+ output_parts.append(heading);
84
+ last_char_pos = insert_pos
85
+
86
+ output_parts.append(edited_transcript[last_char_pos:]);
87
+ result = "".join(output_parts).strip()
88
  print("Transcript formatting complete.")
89
  return result
90
+ # --- End of correction ---
91
+
92
  def format_srt(segments):
93
  srt_content = ""
94
  if not segments: return ""
 
125
  result = response.choices[0].message.content.strip(); print("GPT OK."); return result
126
  except Exception as e: print(f"GPT Error: {e}"); traceback.print_exc(); return f"Chyba GPT: {e}"
127
  def generate_article_content(transcript_state, context_state, article_extra_prompt, progress=gr.Progress(track_tqdm=True)):
 
128
  article_result = "Chyba: Generování článku selhalo."
129
  try:
130
  print("--- generate_article_content called ---")
131
  if not transcript_state or transcript_state.startswith("Chyba:"): return "Chyba: Nelze generovat článek, chybí platný přepis."
132
  if not client: return "Chyba: OpenAI klient není inicializován."
 
133
  progress(0.1, desc="Generování článku..."); print("Generating article...")
134
  word_count = len(str(transcript_state).split()); is_long_article = word_count > 400
 
135
  article_prompt = f"""Jsi zkušený AI redaktor... (plný prompt viz dříve)"""
136
  system_msg = "Jsi špičkový AI redaktor píšící česky..."
137
  progress(0.5, desc="Volání GPT..."); article_result = call_gpt(article_prompt, system_message=system_msg)
138
  progress(1.0, desc="Článek hotov."); print("Article generation OK.")
139
+ except Exception as e: error_message = f"Chyba při generování článku: {e}"; print(error_message); traceback.print_exc(); article_result = error_message
 
 
 
 
 
 
140
  print(f"--- generate_article_content finished, returning: {str(article_result)[:100]}...")
141
+ return article_result
142
  def generate_srt_file(segments_state):
143
  if not segments_state: gr.Warning("Nelze generovat titulky..."); return None, None
144
  print("Generating SRT file..."); srt_content = format_srt(segments_state)
 
156
  print(f"VTT file generated: {vtt_filepath}"); return vtt_filepath, vtt_filepath
157
  except Exception as e: print(f"Error writing VTT file: {e}"); traceback.print_exc(); gr.Error(f"Chyba zápisu VTT: {e}"); return None, None
158
  def create_download_zip(transcript, chapters, reels, srt_path, vtt_path, article):
 
159
  print("Creating ZIP file..."); zip_error = None; zip_path = None; base_filename = "prepisovac_vystupy"
 
160
  if article and not article.startswith("Chyba:"):
161
  title_match = re.search(r"Popisný:\s*\n(.+)", article);
162
  if title_match: extracted_title = title_match.group(1).strip(); sanitized_title = re.sub(r'[\\/*?:"<>|]', "", extracted_title).replace(" ", "_")[:50]
 
179
  shutil.copyfile(zip_filepath, final_zip_path); zip_path = final_zip_path; print(f"ZIP created: {zip_path}")
180
  except Exception as e: zip_error = f"Chyba ZIP: {e}"; print(zip_error); traceback.print_exc(); return None
181
  return zip_path
 
 
182
  def process_audio(audio_filepath, description, keywords, progress=gr.Progress(track_tqdm=True)):
183
+ formatted_transcript_w_chapters = "Probíhá zpracování..."; chapters_formatted = ""; reels_suggestions = ""
184
+ edited_transcript_for_state = ""; context_for_state = ""; segments = []
 
 
 
 
 
 
185
  try:
186
+ progress(0.1, desc="Přepis..."); print(f"Transcribing: {audio_filepath}")
 
187
  if not audio_filepath: raise ValueError("Chybí audio soubor.")
188
+ with open(audio_filepath, "rb") as f: transcription_response = client.audio.transcriptions.create( model=WHISPER_MODEL, file=f, response_format="verbose_json", language=None, timestamp_granularities=["segment"] )
 
189
  if not (transcription_response and hasattr(transcription_response, 'text')): raise Exception(f"Přepis selhal: {transcription_response}")
190
  raw_transcript = transcription_response.text or ""; detected_language = getattr(transcription_response, 'language', 'N/A')
191
  print(f"Transcription OK. Lang: {detected_language}");
192
  if hasattr(transcription_response, 'segments') and transcription_response.segments:
193
+ segments = transcription_response.segments; audio_duration = segments[-1].end if segments else 0; print(f"{len(segments)} segments. Duration: {audio_duration:.2f}s")
194
+ progress(0.3, desc="Přepis OK.")
 
 
 
 
195
  context_parts = [];
196
  if description: context_parts.append(f"Popis: {description}")
197
  if keywords: context_parts.append(f"Klíčová slova: {keywords}")
198
  context_for_state = "\n".join(context_parts) if context_parts else "Žádný kontext."
199
+ progress(0.4, desc="Úprava do CZ..."); print("Editing to CZ...")
200
+ edit_prompt = f"""Jsi profi editor CZ jazyka... (plný prompt viz dříve)"""
201
+ edited_transcript_for_state = call_gpt(edit_prompt, system_message="Jsi editor CZ...")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
202
  if edited_transcript_for_state.startswith("Chyba:"): raise Exception(f"Chyba editace GPT: {edited_transcript_for_state}")
203
  print("Editing OK.")
204
+ progress(0.6, desc="Generování kapitol...")
205
+ parsed_chapters_list = [] # Ensure defined
206
+ chapters_formatted = "Kapitoly nebyly vygenerovány."
 
 
 
 
207
  if segments:
 
208
  print("Generating chapters...");
209
+ if audio_duration < 60: num_chapters = 1
210
  elif audio_duration < 600: num_chapters = 3
211
  elif audio_duration < 1800: num_chapters = random.randint(5, 7)
212
  else: num_chapters = random.randint(7, 10)
 
213
  try:
214
+ chapter_prompt = f"""Jsi AI pro YT kapitoly... PŘESNĚ {num_chapters}... (plný prompt viz dříve)"""
215
+ chapters_raw = call_gpt(chapter_prompt, system_message="Jsi AI expert na YT kapitoly...")
 
 
 
 
 
 
 
 
216
  print(f"Raw Chapters Output from GPT:\n---\n{chapters_raw}\n---")
217
  if not chapters_raw.startswith("Chyba:") and "ŽÁDNÉ KAPITOLY" not in chapters_raw:
218
+ parsed_chapters_list = parse_chapters(chapters_raw) # Uses corrected parse_chapters
219
  if parsed_chapters_list:
220
  chapters_formatted_list = [f"{format_yt_timestamp(ch['time'])} - {ch['title']}" for ch in parsed_chapters_list]
221
  chapters_formatted = "\n".join(chapters_formatted_list); print("Chapters OK.")
222
  else: chapters_formatted = "Nepodařilo se rozpoznat formát kapitol."; print("Chapter parsing failed.")
223
+ elif "ŽÁDNÉ KAPITOLY" in chapters_raw: chapters_formatted = "Pro tento text nebyly nalezeny žádné smysluplné kapitoly."; print("GPT indicated no chapters found.")
224
+ else: chapters_formatted = chapters_raw; print(f"Chapter gen error: {chapters_formatted}")
 
 
 
225
  except Exception as e: chapters_formatted = f"Chyba kapitol: {e}"; print(chapters_formatted); traceback.print_exc()
226
+ else: chapters_formatted = "Kapitoly nelze (chybí segmenty)..."; print(chapters_formatted)
227
+ progress(0.8, desc="Generování Reels...")
228
+ reels_suggestions = "Návrhy pro Reels nebyly vygenerovány."
 
 
229
  if edited_transcript_for_state and not edited_transcript_for_state.startswith("Chyba:"):
 
230
  print("Generating Reels suggestions...")
231
  try:
232
+ reels_prompt = f"""Jsi AI pro Reels/TikTok... (plný prompt viz dříve)"""
233
+ reels_result = call_gpt(reels_prompt, system_message="Jsi AI expert na Reels...")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
234
  if not reels_result.startswith("Chyba:") and "Čas:" in reels_result and "Popis:" in reels_result:
235
  reels_suggestions = reels_result; print("Reels OK.")
236
  else: print(f"Reels output unexpected or error: {reels_result[:200]}...")
237
  except Exception as e: reels_suggestions = f"Chyba Reels: {e}"; print(reels_suggestions); traceback.print_exc()
238
+ progress(0.9, desc="Formátování výstupu...")
239
+ # Use the possibly updated parsed_chapters_list here
240
+ formatted_transcript_w_chapters = format_transcript_with_chapters(edited_transcript_for_state, parsed_chapters_list)
 
 
 
 
 
241
  progress(1.0, desc="Hotovo!"); print("Processing OK.")
242
+ return formatted_transcript_w_chapters, chapters_formatted, reels_suggestions, edited_transcript_for_state, context_for_state, segments, chapters_formatted, reels_suggestions
 
 
 
 
 
 
243
  except Exception as e:
244
  error_message = f"Chyba během zpracování: {e}"; print(error_message); traceback.print_exc()
 
245
  return error_message, "", "", "", "", [], "", ""
246
 
 
247
  # --- Gradio Interface Definition ---
248
+ theme = gr.themes.Default()
249
 
250
  # --- Build Gradio UI ---
251
  with gr.Blocks(theme=theme) as demo:
 
287
  download_file_output = gr.File(label="Stažený ZIP", interactive=False, visible=False)
288
 
289
  # --- Event Handling ---
290
+ # (Event handling remains the same)
291
  submit_button.click(
292
  fn=process_audio, inputs=[audio_input, description_input, keywords_input],
293
  outputs=[ edited_output_formatted, chapters_output, reels_output, transcript_state, context_state, segments_state, chapters_state, reels_state ] )