Spaces:
Build error

Surficata commited on
Commit
3dbe540
·
verified ·
1 Parent(s): fa8d862

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +395 -776
app.py CHANGED
@@ -6,15 +6,14 @@ import datetime
6
  import tempfile
7
  import traceback
8
  import math
9
- import random
10
- import re
11
  import zipfile
12
  import shutil
 
13
 
14
  # --- Configuration & OpenAI Client Setup ---
15
  OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
16
  WHISPER_MODEL = "whisper-1"
17
- # <<< CHANGE: Use the new GPT-4.1 model >>>
18
  GPT_MODEL = "gpt-4.1"
19
  client = None
20
  if OPENAI_API_KEY:
@@ -28,686 +27,381 @@ else:
28
 
29
  # --- Helper Functions ---
30
 
 
31
  def format_timestamp(seconds, format_type='srt', precision='milliseconds'):
32
- """Formats seconds into HH:MM:SS,ms or HH:MM:SS format."""
33
- if not isinstance(seconds, (int, float)) or seconds < 0:
34
- seconds = 0
35
- seconds_int = int(seconds)
36
- milliseconds_part = seconds - seconds_int
37
- milliseconds = int(milliseconds_part * 1000)
38
- td = datetime.timedelta(seconds=seconds_int)
39
- total_seconds = int(td.total_seconds())
40
- hours, remainder = divmod(total_seconds, 3600)
41
- minutes, seconds_rem = divmod(remainder, 60)
42
-
43
- if precision == 'seconds':
44
- return f"{hours:02}:{minutes:02}:{seconds_rem:02}"
45
- else:
46
- separator = ',' if format_type == 'srt' else '.'
47
- return f"{hours:02}:{minutes:02}:{seconds_rem:02}{separator}{milliseconds:03}"
48
 
49
  def format_yt_timestamp(seconds):
50
- """Formats seconds into YouTube chapter format (MM:SS or H:MM:SS)."""
51
- if not isinstance(seconds, (int, float)) or seconds < 0:
52
- seconds = 0
53
- td = datetime.timedelta(seconds=int(seconds))
54
- total_seconds = int(td.total_seconds())
55
- hours, remainder = divmod(total_seconds, 3600)
56
- minutes, seconds_rem = divmod(remainder, 60)
57
- if hours > 0:
58
- return f"{hours}:{minutes:02}:{seconds_rem:02}"
59
- else:
60
- return f"{minutes:02}:{seconds_rem:02}"
61
 
 
62
  def parse_chapters(chapter_text):
63
  """Parses chapter text (HH:MM:SS - Title) into a list of dictionaries."""
64
  chapters = []
65
- # Pattern to match HH:MM:SS or MM:SS at the start of a line, followed by ' - ' and title
66
  pattern = re.compile(r"^(?:(\d{1,2}):)?(\d{1,2}):(\d{2})\s*-\s*(.+)$", re.MULTILINE)
67
- if not chapter_text:
68
- return chapters
69
- print(f"Parsing chapter text:\n---\n{chapter_text}\n---")
70
  for match in pattern.finditer(chapter_text):
71
  try:
72
- hours_str = match.group(1)
73
- minutes_str = match.group(2)
74
- seconds_str = match.group(3)
75
- title = match.group(4).strip()
76
-
77
- hours = int(hours_str) if hours_str else 0
78
- minutes = int(minutes_str) if minutes_str else 0
79
- seconds = int(seconds_str) if seconds_str else 0
80
-
81
- # Basic validation for minutes and seconds
82
- if not (0 <= minutes < 60 and 0 <= seconds < 60):
83
- print(f"Skipping invalid time format in chapter: '{match.group(0)}'")
84
- continue
85
-
86
  total_seconds = hours * 3600 + minutes * 60 + seconds
87
  chapters.append({"time": total_seconds, "title": title})
88
- except Exception as e:
89
- print(f"Error parsing chapter line: '{match.group(0)}' - {e}")
90
-
91
- # Sort chapters by time
92
- try:
93
- chapters.sort(key=lambda x: x['time'])
94
- except Exception as e:
95
- print(f"Error sorting chapters: {e}")
96
-
97
- print(f"Parsed chapters: {chapters}")
98
  return chapters
99
 
100
- # <<< CHANGE: Modified function to accept optional duration estimate >>>
101
- def format_transcript_with_chapters(edited_transcript, parsed_chapters, audio_duration_estimate=None):
102
- """Formats transcript with chapter headings, optionally using a duration estimate."""
103
- if not parsed_chapters or not edited_transcript: return edited_transcript
104
  output_parts = []; last_char_pos = 0; total_len = len(edited_transcript)
 
105
 
106
- # Use provided estimate, otherwise fallback to estimating from last chapter or default
107
- if audio_duration_estimate is None or audio_duration_estimate <= 0:
108
- # Estimate duration based on the time of the last chapter + buffer, or default to 1 hour
109
- audio_duration_estimate = parsed_chapters[-1]['time'] + 60 if parsed_chapters else 3600
110
- print(f"Warning: Using fallback duration estimate for chapter formatting: {audio_duration_estimate:.0f}s")
111
- print(f"Formatting transcript with chapters using estimated duration: {audio_duration_estimate:.0f}s")
112
-
113
- # Estimate character position based on time and estimated duration
114
  for i, chapter in enumerate(parsed_chapters):
115
- approx_char_pos = int((chapter['time'] / audio_duration_estimate) * total_len) if audio_duration_estimate > 0 else 0
116
- # Heuristic to find a nearby newline before the estimated position
117
- # Look back up to 300 chars or half the distance from last pos, whichever is smaller
 
 
 
118
  search_window_start = max(last_char_pos, approx_char_pos - min(300, (approx_char_pos - last_char_pos) // 2 if (approx_char_pos - last_char_pos) > 0 else 100))
119
  insert_pos = edited_transcript.rfind('\n', search_window_start, approx_char_pos)
120
-
121
  if insert_pos == -1 or insert_pos < last_char_pos:
122
- # If no newline found before, try finding one shortly after (up to 100 chars)
123
  insert_pos = edited_transcript.find('\n', approx_char_pos, approx_char_pos + 100)
124
- if insert_pos == -1: # Still no newline? Insert at the approximate position.
125
- # Try to at least break at a space before the approx position if possible
126
  space_pos = edited_transcript.rfind(' ', search_window_start, approx_char_pos)
127
- if space_pos != -1 and space_pos > last_char_pos:
128
- insert_pos = space_pos + 1 # Insert after space
129
- else:
130
- insert_pos = approx_char_pos # Fallback to approx position
131
- else:
132
- insert_pos += 1 # Insert after the newline
133
- else:
134
- insert_pos += 1 # Insert after the newline found before
135
-
136
- # Ensure position is valid and moves forward
137
  insert_pos = min(max(last_char_pos, insert_pos), total_len)
138
 
139
  output_parts.append(edited_transcript[last_char_pos:insert_pos])
140
- # Ensure heading is not placed right at the beginning if first chapter is at 0s
141
  heading_prefix = "\n\n" if insert_pos > 0 else ""
142
- heading = f"{heading_prefix}({format_timestamp(chapter['time'], precision='seconds')} - {chapter['title']})\n"
143
- output_parts.append(heading)
144
- last_char_pos = insert_pos
145
 
146
  output_parts.append(edited_transcript[last_char_pos:])
147
  result = "".join(output_parts).strip()
148
- print("Transcript formatting complete.")
149
  return result
150
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
151
  def format_srt(segments):
152
- """Formats Whisper segments into SRT subtitle format."""
153
- srt_content = ""
154
- if not segments:
155
- return ""
156
- for i, segment in enumerate(segments):
157
- # Check if segment has the expected attributes
158
- if not all(hasattr(segment, attr) for attr in ['start', 'end', 'text']):
159
- print(f"SRT segment {i} missing attributes: {segment}")
160
- continue
161
- try:
162
- start_time = format_timestamp(segment.start, 'srt')
163
- end_time = format_timestamp(segment.end, 'srt')
164
- text = segment.text.strip() if segment.text else ""
165
-
166
- # Simple line breaking (adjust max_length as needed)
167
- max_length = 42
168
- words = text.split()
169
- lines = []
170
- current_line = ""
171
- for word in words:
172
- if not current_line:
173
- current_line = word
174
- elif len(current_line) + len(word) + 1 <= max_length:
175
- current_line += " " + word
176
- else:
177
- lines.append(current_line)
178
- current_line = word
179
- if current_line: # Append the last line
180
- lines.append(current_line)
181
-
182
- formatted_text = "\n".join(l for l in lines if l) # Ensure no empty lines
183
- if formatted_text: # Only add segment if there is text
184
- srt_content += f"{i + 1}\n{start_time} --> {end_time}\n{formatted_text}\n\n"
185
-
186
- except Exception as e: # Catch potential errors during formatting
187
- print(f"Error formatting SRT segment {i}: {e} - Segment data: {segment}")
188
- continue
189
  return srt_content
190
 
191
  def format_vtt(segments):
192
- """Formats Whisper segments into VTT subtitle format."""
193
- vtt_content = "WEBVTT\n\n"
194
- if not segments:
195
- return vtt_content
196
- for i, segment in enumerate(segments):
197
- # Check if segment has the expected attributes
198
- if not all(hasattr(segment, attr) for attr in ['start', 'end', 'text']):
199
- print(f"VTT segment {i} missing attributes: {segment}")
200
- continue
201
- try:
202
- start_time = format_timestamp(segment.start, 'vtt')
203
- end_time = format_timestamp(segment.end, 'vtt')
204
- text = segment.text.strip() if segment.text else ""
205
-
206
- # Simple line breaking (adjust max_length as needed)
207
- max_length = 42
208
- words = text.split()
209
- lines = []
210
- current_line = ""
211
- for word in words:
212
- if not current_line:
213
- current_line = word
214
- elif len(current_line) + len(word) + 1 <= max_length:
215
- current_line += " " + word
216
- else:
217
- lines.append(current_line)
218
- current_line = word
219
- if current_line: # Append the last line
220
- lines.append(current_line)
221
-
222
- formatted_text = "\n".join(l for l in lines if l) # Ensure no empty lines
223
- if formatted_text: # Only add segment if there is text
224
- vtt_content += f"{start_time} --> {end_time}\n{formatted_text}\n\n"
225
-
226
- except Exception as e: # Catch potential errors during formatting
227
- print(f"Error formatting VTT segment {i}: {e} - Segment data: {segment}")
228
- continue
229
  return vtt_content
230
 
 
231
  def call_gpt(prompt, system_message="Jsi užitečný AI asistent."):
232
- """Calls the OpenAI Chat Completions API."""
233
- if not client:
234
- print("Error: OpenAI client not initialized.")
235
- return "Chyba: OpenAI klient není inicializován. Zkontrolujte API klíč."
236
  try:
237
- print(f"Calling GPT Model: {GPT_MODEL}...")
238
- # Make sure your OpenAI library version supports the model you are calling
239
- response = client.chat.completions.create(
240
- model=GPT_MODEL,
241
- messages=[
242
- {"role": "system", "content": system_message},
243
- {"role": "user", "content": prompt}
244
- ]
245
- # Consider adding temperature, max_tokens if needed, but defaults are often fine
246
- )
247
- result = response.choices[0].message.content.strip()
248
- print("GPT Call OK.")
249
- # Basic check if the result seems empty or too short (might indicate an issue)
250
- if not result or len(result) < 10:
251
- print(f"Warning: GPT returned a very short or empty response: '{result}'")
252
  return result
253
- except openai.NotFoundError as e:
254
- print(f"GPT Error: Model '{GPT_MODEL}' not found or not accessible with your API key. {e}")
255
- traceback.print_exc()
256
- return f"Chyba GPT: Model '{GPT_MODEL}' nenalezen nebo není dostupný. Zkontrolujte název modelu a váš API klíč."
257
- except openai.RateLimitError as e:
258
- print(f"GPT Error: Rate limit exceeded. {e}")
259
- traceback.print_exc()
260
- return f"Chyba GPT: Překročen limit požadavků (Rate Limit). Zkuste to prosím později."
261
- except openai.APIConnectionError as e:
262
- print(f"GPT Error: Network issue connecting to OpenAI. {e}")
263
- traceback.print_exc()
264
- return f"Chyba GPT: Problém s připojením k OpenAI. Zkontrolujte síť."
265
- except Exception as e:
266
- print(f"An unexpected GPT Error occurred: {e}")
267
- traceback.print_exc()
268
- return f"Chyba GPT: Neočekávaná chyba - {e}"
269
 
 
270
  def generate_article_content(transcript_state, context_state, article_extra_prompt, progress=gr.Progress(track_tqdm=True)):
271
- """Generates structured article content using GPT based on the transcript."""
272
  article_result = "Chyba: Generování článku selhalo."
273
  try:
274
  print("--- generate_article_content called ---")
275
- if not transcript_state or transcript_state.startswith("Chyba:"):
276
- return "Chyba: Nelze generovat článek bez platného přepisu.", "Chyba: Nelze generovat článek bez platného přepisu."
277
- if not client:
278
- return "Chyba: OpenAI klient není inicializován.", "Chyba: OpenAI klient není inicializován."
279
-
280
  progress(0.1, desc="Příprava na generování článku..."); print("Generating article...")
281
- # Estimate word count for deciding article structure points
282
- word_count = len(str(transcript_state).split())
283
- is_long_article = word_count > 400 # Simple threshold
284
-
285
- # --- REVISED ARTICLE PROMPT v3 ---
286
- article_prompt = f"""POKYN: Jsi AI redaktor specializovaný na tvorbu obsahu z podcastů a rozhovorů. Vygeneruj komplexní výstup POUZE ve formátu čistého textu (žádný Markdown) v ČEŠTINĚ na základě VSTUPŮ níže. Striktně dodrž požadovaný formát a strukturu.
287
-
288
- == VSTUP: Kontext ==
289
- {context_state if context_state else "Není k dispozici."}
290
 
291
  == VSTUP: Editovaný přepis ==
292
  --- START ---
293
  {transcript_state}
294
  --- END ---
295
-
296
- == VSTUP: Extra pokyny od uživatele ==
297
- {article_extra_prompt if article_extra_prompt else "Žádné specifické pokyny."}
298
-
299
- == POŽADOVANÝ VÝSTUP (Striktně dodrž formát!) ==
300
-
301
- Sociální sítě:
302
- (Vytvoř 3 stručné, poutavé verze s relevantními emoji 📱👍🤔 a 2-3 relevantními #hashtagy pro každou)
303
- Verze A (Krátká, úderná): [Text krátké verze]
304
- Verze B (Informativní, shrnutí): [Text informativní verze]
305
- Verze C (Otázka nebo zajímavost): [Text originální/otázka verze]
306
-
307
- Návrhy titulků:
308
- (Vytvoř PŘESNĚ 5 variant, každou na novém řádku, formát 'Typ:\\nNázev')
309
- Popisný:
310
- [Název popisného titulku vystihující hlavní téma]
311
- Výrazný:
312
- [Název výrazného, možná kontroverzního nebo zvědavost budícího titulku]
313
- Citace:
314
- [Krátká, silná citace z textu jako titulek v uvozovkách]
315
- Emotivní:
316
- [Název titulku apelující na emoce nebo osobní zkušenost]
317
- Otázka:
318
- [Zajímavá otázka týkající se obsahu jako titulek]
319
-
320
- Článek:
321
-
322
- Perex
323
- (Napiš výstižný perex o rozsahu cca 4-6 vět, který shrne nejdůležitější body a naláká ke čtení.)
324
- [Text perexu...]
325
-
326
- Co se dozvíte
327
- ({"Vytvoř 5-7 klíčových bodů (použij odrážku '-') shrnujících hlavní informace nebo témata článku." if is_long_article else "Vytvoř 3-5 klíčových bodů (použij odrážku '-') shrnujících hlavní informace nebo témata článku."})
328
- - [Bod 1]
329
- - [Bod 2]
330
- ...
331
-
332
- [Mezititulek 1 - Výstižný název v češtině]
333
- (Napiš první část článku. Použij relevantní české mezititulky. Zahrň **hodně přímých citací** z poskytnutého přepisu v „českých uvozovkách“, aby byl text autentický. Text by měl být čtivý, logicky strukturovaný a rozvíjet témata z perexu a bodů.)
334
- [Text oddílu 1...]
335
-
336
- [Mezititulek 2 - Výstižný název v češtině]
337
- (Pokračuj v článku dalším oddílem s mezititulkem a citacemi.)
338
- [Text oddílu 2...]
339
-
340
- (... pokračuj s dalšími mezititulky podle potřeby, aby byl článek přehledný a pokrýval hlavní témata z přepisu ...)
341
-
342
- [Závěrečný mezititulek nebo Shrnutí]
343
- (Krátké shrnutí nebo závěrečná myšlenka.)
344
- [Text závěrečného oddílu...]
345
-
346
- == KONEC SPECIFIKACE VÝSTUPU ==
347
-
348
- GENERUJ NYNÍ POUZE POŽADOVANÝ VÝSTUP V ČEŠTINĚ. ZAČNI PŘÍMO SEKCI 'Sociální sítě:'. NEODPOVÍDEJ KONVERZAČNĚ. NEPOKLÁDEJ OTÁZKY. NEKOMENTUJ STRUKTURU.
349
- """
350
- # --- REVISED SYSTEM MESSAGE v3 ---
351
- system_msg = "Tvojí jedinou rolí je generovat strukturovaný textový výstup v češtině přesně podle formátu a instrukcí v uživatelském promptu. Negeneruješ žádný jiný text, otázky ani komentáře. Soustředíš se na kvalitu a relevanci obsahu."
352
-
353
  progress(0.5, desc=f"Volání GPT ({GPT_MODEL})...");
354
  article_result = call_gpt(article_prompt, system_message=system_msg)
355
-
356
- if article_result.startswith("Chyba GPT:") or not article_result or len(article_result) < 100:
357
- raise Exception(f"Generování článku selhalo nebo vrátilo neplatný výsledek: {article_result}")
358
-
359
  progress(1.0, desc="Článek vygenerován."); print("Article generation OK.")
360
-
361
- except Exception as e:
362
- error_message = f"Chyba při generování článku: {e}"
363
- print(error_message)
364
- traceback.print_exc()
365
- article_result = error_message # Keep the error message for display
366
-
367
  print(f"--- generate_article_content finished, returning result starting with: {str(article_result)[:150]}...")
368
- # Return the result for both the display and the state
369
  return article_result, article_result
370
 
 
 
371
  def generate_srt_file(segments_state):
372
- """Generates an SRT file from segments and returns its temporary path."""
373
- if not segments_state:
374
- gr.Warning("Nelze generovat SRT titulky - chybí data segmentů (nebylo zpracováno audio?).")
375
- return None, None # Return None for both file output and state path
376
- print("Generating SRT file...")
377
- srt_content = format_srt(segments_state)
378
- if not srt_content:
379
- gr.Warning("Nepodařilo se vygenerovat obsah SRT (žádné platné segmenty?).")
380
- return None, None
381
  try:
382
- # Create a temporary file for the SRT content
383
- with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.srt', encoding='utf-8', prefix='sub_') as f:
384
- f.write(srt_content)
385
- srt_filepath = f.name
386
- print(f"SRT file generated temporarily at: {srt_filepath}")
387
- # Return the path for download and for state
388
- return srt_filepath, srt_filepath
389
- except Exception as e:
390
- error_msg = f"Chyba při zápisu dočasného SRT souboru: {e}"
391
- print(error_msg)
392
- traceback.print_exc()
393
- gr.Error(error_msg)
394
- return None, None
395
 
396
  def generate_vtt_file(segments_state):
397
- """Generates a VTT file from segments and returns its temporary path."""
398
- if not segments_state:
399
- gr.Warning("Nelze generovat VTT titulky - chybí data segmentů (nebylo zpracováno audio?).")
400
- return None, None # Return None for both file output and state path
401
- print("Generating VTT file...")
402
- vtt_content = format_vtt(segments_state)
403
- # Check if content is more than just the header
404
- if not vtt_content or vtt_content.strip() == "WEBVTT":
405
- gr.Warning("Nepodařilo se vygenerovat obsah VTT (žádné platné segmenty?).")
406
- return None, None
407
  try:
408
- # Create a temporary file for the VTT content
409
- with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.vtt', encoding='utf-8', prefix='sub_') as f:
410
- f.write(vtt_content)
411
- vtt_filepath = f.name
412
- print(f"VTT file generated temporarily at: {vtt_filepath}")
413
- # Return the path for download and for state
414
- return vtt_filepath, vtt_filepath
415
- except Exception as e:
416
- error_msg = f"Chyba při zápisu dočasného VTT souboru: {e}"
417
- print(error_msg)
418
- traceback.print_exc()
419
- gr.Error(error_msg)
420
- return None, None
421
 
422
- def create_download_zip(transcript, chapters, reels, srt_path, vtt_path, article):
 
423
  """Creates a ZIP file containing all generated outputs."""
424
  print("Attempting to create ZIP file...")
425
- zip_error = None
426
  final_zip_path = None
427
- base_filename = "prepisovac_vystupy" # Default filename base
428
 
429
- # Try to extract a title from the article to use as filename base
430
  if article and isinstance(article, str) and not article.startswith("Chyba:"):
431
- # Look for the "Popisný:" title first
432
  title_match = re.search(r"Popisný:\s*\n(.+)", article, re.IGNORECASE)
433
- if not title_match:
434
- # Fallback: Look for the first line after "Návrhy titulků:"
435
- title_match = re.search(r"Návrhy titulků:\s*\n(?:.+\:\s*\n)?(.+)", article, re.IGNORECASE)
436
  if title_match:
437
- extracted_title = title_match.group(1).strip()
438
- # Sanitize the title for use in a filename
439
- sanitized_title = re.sub(r'[\\/*?:"<>|]', "", extracted_title) # Remove invalid chars
440
- sanitized_title = re.sub(r'\s+', '_', sanitized_title) # Replace spaces with underscores
441
- base_filename = sanitized_title[:50] # Limit length
442
  print(f"Using base filename from article title: '{base_filename}'")
443
- else:
444
- print("Could not extract title from article, using default filename.")
445
 
446
  try:
447
- # Use a temporary directory to store files before zipping
448
  with tempfile.TemporaryDirectory() as temp_dir:
449
- zip_filename = f"{base_filename}.zip"
450
- zip_filepath = os.path.join(temp_dir, zip_filename)
451
  print(f"Creating zip archive at: {zip_filepath}")
452
-
453
  files_added_count = 0
454
  with zipfile.ZipFile(zip_filepath, 'w', zipfile.ZIP_DEFLATED) as zipf:
455
- # Add Edited Transcript
456
- if transcript and isinstance(transcript, str) and not transcript.startswith("Chyba:"):
457
- t_filename = "prepis_editovany.txt"
458
- t_filepath = os.path.join(temp_dir, t_filename)
459
- with open(t_filepath, 'w', encoding='utf-8') as f: f.write(transcript)
460
- zipf.write(t_filepath, t_filename)
461
- print(f"Added '{t_filename}' to zip.")
462
- files_added_count += 1
463
-
464
- # Add Chapters
465
- if chapters and isinstance(chapters, str) and not chapters.startswith("Chyba:") and "ŽÁDNÉ KAPITOLY" not in chapters and "Nepodařilo se rozpoznat" not in chapters:
466
- c_filename = "kapitoly_youtube.txt"
467
- c_filepath = os.path.join(temp_dir, c_filename)
468
- with open(c_filepath, 'w', encoding='utf-8') as f: f.write(chapters)
469
- zipf.write(c_filepath, c_filename)
470
- print(f"Added '{c_filename}' to zip.")
471
- files_added_count += 1
472
-
473
- # Add Reels Suggestions
474
- if reels and isinstance(reels, str) and not reels.startswith("Chyba:") and "ŽÁDNÉ NÁVRHY" not in reels and "Nebyly nalezeny" not in reels:
475
- r_filename = "navrhy_reels.txt"
476
- r_filepath = os.path.join(temp_dir, r_filename)
477
- with open(r_filepath, 'w', encoding='utf-8') as f: f.write(reels)
478
- zipf.write(r_filepath, r_filename)
479
- print(f"Added '{r_filename}' to zip.")
480
- files_added_count += 1
481
 
482
  # Add Article
483
  if article and isinstance(article, str) and not article.startswith("Chyba:"):
484
- a_filename = "clanek_navrh.txt"
485
- a_filepath = os.path.join(temp_dir, a_filename)
486
  with open(a_filepath, 'w', encoding='utf-8') as f: f.write(article)
487
- zipf.write(a_filepath, a_filename)
488
- print(f"Added '{a_filename}' to zip.")
489
- files_added_count += 1
490
-
491
- # Add SRT file (if path exists and is a string)
492
- if srt_path and isinstance(srt_path, str) and os.path.exists(srt_path):
493
- srt_filename = f"{base_filename}.srt"
494
- print(f"Adding SRT file: {srt_path} as {srt_filename}")
495
- zipf.write(srt_path, srt_filename)
496
- files_added_count += 1
497
- elif srt_path:
498
- print(f"Skipping SRT file (Path invalid or not found: {srt_path})")
499
-
500
- # Add VTT file (if path exists and is a string)
501
- if vtt_path and isinstance(vtt_path, str) and os.path.exists(vtt_path):
502
- vtt_filename = f"{base_filename}.vtt"
503
- print(f"Adding VTT file: {vtt_path} as {vtt_filename}")
504
- zipf.write(vtt_path, vtt_filename)
505
- files_added_count += 1
506
- elif vtt_path:
507
- print(f"Skipping VTT file (Path invalid or not found: {vtt_path})")
508
-
509
- # If no files were added, add a placeholder info file
510
  if files_added_count == 0:
511
- placeholder_filename = "info.txt"
512
- placeholder_filepath = os.path.join(temp_dir, placeholder_filename)
513
- with open(placeholder_filepath, 'w', encoding='utf-8') as f:
514
- f.write("Nebyly nalezeny žádné platné výstupy k zahrnutí do tohoto ZIP archivu.\n")
515
- f.write("Možné důvody:\n")
516
- f.write("- Zpracování selhalo nebo nebylo spuštěno.\n")
517
- f.write("- Nebyly vygenerovány žádné volitelné výstupy (článek, titulky).\n")
518
- f.write("- Při generování došlo k chybám.\n")
519
- zipf.write(placeholder_filepath, placeholder_filename)
520
- print("No valid outputs found, added info.txt to zip.")
521
- gr.Info("ZIP archiv neobsahuje žádné platné výstupy.")
522
-
523
- # Copy the zip file from the temporary directory to a place Gradio can serve
524
- # Using NamedTemporaryFile to get a persistent path outside the TemporaryDirectory context
525
- final_zip_path_obj = tempfile.NamedTemporaryFile(delete=False, suffix='.zip', prefix=f"{base_filename}_")
526
- final_zip_path = final_zip_path_obj.name
527
- final_zip_path_obj.close() # Close the file handle
528
- shutil.copyfile(zip_filepath, final_zip_path)
529
- print(f"ZIP file successfully created and copied to: {final_zip_path}")
530
- gr.Info(f"ZIP soubor '{os.path.basename(final_zip_path)}' připraven ke stažení.")
531
 
532
- except Exception as e:
533
- zip_error = f"Chyba při vytváření ZIP archivu: {e}"
534
- print(zip_error)
535
- traceback.print_exc()
536
- gr.Error(zip_error)
537
- return None # Return None if zip creation failed
538
 
539
- # Return the path to the final zip file for the download component
 
 
540
  return final_zip_path
541
 
542
 
543
  # --- Main Processing Function ---
544
- # <<< CHANGE: Function updated to handle text/file input and skip Whisper >>>
545
- def process_audio(audio_filepath, description, keywords, transcript_text_input, transcript_file_input, progress=gr.Progress(track_tqdm=True)):
546
- """Processes either an audio file via Whisper or a directly provided transcript."""
547
- formatted_transcript_w_chapters = "Probíhá zpracování..."
548
- chapters_formatted = ""
549
- reels_suggestions = ""
 
 
550
  edited_transcript_for_state = ""
551
  context_for_state = ""
552
- segments = [] # Initialize as empty list
 
553
  raw_transcript = None
554
- audio_duration = 0 # Initialize duration
555
- estimated_duration_override = None # For passing estimate to formatting function
556
 
557
  try:
558
- # --- INPUT SELECTION ---
559
- # Priority: File > Textbox > Audio
560
  input_source = "Neznámý"
561
- if transcript_file_input is not None:
562
- input_source = "Soubor s přepisem"
563
- print(f"Processing provided transcript file: {transcript_file_input.name}")
 
 
564
  try:
565
- # Use .name attribute for the temp file path provided by gr.File
566
- with open(transcript_file_input.name, 'r', encoding='utf-8') as f:
567
- raw_transcript = f.read()
568
- if not raw_transcript or not raw_transcript.strip():
569
- raise ValueError("Soubor s přepisem je prázdný.")
570
- audio_filepath = None # Signal to skip Whisper
571
- detected_language = "N/A (Přepis dodán ze souboru)"
572
- gr.Info(f"Zpracovávám přepis ze souboru: {os.path.basename(transcript_file_input.name)}")
573
- except Exception as e:
574
- raise ValueError(f"Chyba při čtení souboru s přepisem: {e}")
575
-
576
- elif transcript_text_input and transcript_text_input.strip():
577
- input_source = "Vložený text přepisu"
578
- print("Processing provided transcript text...")
579
- raw_transcript = transcript_text_input.strip()
580
- audio_filepath = None # Signal to skip Whisper
581
- detected_language = "N/A (Přepis dodán z textového pole)"
582
- gr.Info("Zpracovávám přepis z textového pole.")
 
 
583
 
584
  elif audio_filepath is not None:
585
- input_source = "Audio soubor"
586
- print(f"Processing audio file: {audio_filepath}")
587
- if not client: raise Exception("OpenAI klient není inicializován pro přepis.")
588
- progress(0.1, desc="Přepis (Whisper)...");
589
- print(f"Transcribing: {audio_filepath}")
590
- gr.Info("Spouštím přepis audio souboru...")
591
- # Check file size before uploading
592
- try:
593
- file_size = os.path.getsize(audio_filepath)
594
- # Whisper API limit is 25 MiB (25 * 1024 * 1024 bytes)
595
- if file_size > 25 * 1024 * 1024:
596
- # --- AUDIO CHUNKING NEEDED HERE for >25MB files ---
597
- # This part is NOT implemented in this version
598
- # For now, just raise an error
599
- raise ValueError(f"Audio soubor ({file_size / 1024 / 1024:.1f} MB) je příliš velký pro přímé zpracování Whisper API (limit 25MB). Pro delší audio použijte možnost vložení/nahrání hotového přepisu.")
600
- except OSError as e:
601
- print(f"Warning: Could not check file size - {e}")
602
-
603
- with open(audio_filepath, "rb") as f:
604
- transcription_response = client.audio.transcriptions.create(
605
- model=WHISPER_MODEL,
606
- file=f,
607
- response_format="verbose_json",
608
- language=None, # Let Whisper detect
609
- timestamp_granularities=["segment"]
610
- )
611
- if not (transcription_response and hasattr(transcription_response, 'text')):
612
- raise Exception(f"Přepis Whisper selhal nebo vrátil neočekávanou odpověď: {transcription_response}")
613
-
614
- raw_transcript = transcription_response.text or ""
615
- detected_language = getattr(transcription_response, 'language', 'N/A')
616
- print(f"Transcription OK. Detected Lang: {detected_language}")
617
-
618
- if hasattr(transcription_response, 'segments') and transcription_response.segments:
619
- # Filter out potential problematic segments (e.g., None values if API glitch occurs)
620
- segments = [seg for seg in transcription_response.segments if seg and hasattr(seg, 'start') and hasattr(seg, 'end') and hasattr(seg, 'text')]
621
- if segments: # Ensure segments list is not empty after filtering
622
- audio_duration = segments[-1].end
623
- print(f"Received {len(segments)} valid segments. Estimated Duration: {audio_duration:.2f}s")
624
- else:
625
- print("Warning: No valid segments found in Whisper response.")
626
- audio_duration = 0 # Set duration to 0 if no segments
627
- else:
628
- print("Warning: Segments not found in Whisper response.")
629
- progress(0.2, desc="Přepis dokončen.")
630
- gr.Info(f"Přepis audia dokončen (jazyk: {detected_language}).")
631
-
632
- else:
633
- # No input provided at all
634
- gr.Warning("Nebyl poskytnut žádný vstup (audio, text ani soubor). Zadejte prosím vstup a zkuste to znovu.")
635
- # Return empty values for all outputs to clear the UI
636
- return "", "", "", "", "", [], "", ""
637
-
638
- # --- VALIDATE RAW TRANSCRIPT ---
639
- if raw_transcript is None or not raw_transcript.strip():
640
- raise ValueError(f"Získaný přepis (zdroj: {input_source}) je prázdný nebo neplatný.")
641
-
642
- print(f"Surový přepis připraven (Zdroj: {input_source}, Délka: {len(raw_transcript)} znaků). Pokračuji editací...")
643
 
644
  # --- CONTEXT PREPARATION ---
645
  context_parts = [];
646
  if description and description.strip(): context_parts.append(f"Popis: {description.strip()}")
647
  if keywords and keywords.strip(): context_parts.append(f"Klíčová slova: {keywords.strip()}")
648
- context_for_state = "\n".join(context_parts) if context_parts else "Žádný kontext nebyl poskytnut."
649
- print(f"Context for GPT: {context_for_state}")
650
-
651
- # --- EDITING (Uses raw_transcript, now uses GPT_MODEL = "gpt-4.1") ---
652
- progress(0.3, desc=f"Úprava textu ({GPT_MODEL})...");
653
- print(f"Editing transcript using {GPT_MODEL}...")
654
- gr.Info("Spouštím úpravu a překlad textu pomocí GPT...")
655
- # Edit prompt remains the same, ensure it uses the full raw_transcript
656
- 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ů, pochází z '{input_source}') a upravit ho do podoby perfektního, čtivého a gramaticky správného redakčního textu VŽDY V ČEŠTINĚ.
657
-
658
- Pravidla úprav:
659
- - 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.
660
- - 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.
661
- - Oprav veškeré gramatické chyby, překlepy a interpunkci v češtině.
662
- - Odstraň slovní vatu, hezitace (ehm, hmm), opakující se slova, nedokončené věty (pokud nemají význam).
663
- - Vytvoř logické odstavce pro lepší čitelnost.
664
- - Použij kontext (pokud je k dispozici) a klíčová slova pro opravu/správné psaní specifických termínů a jmen.
665
- - Zachovej původní smysl a informace. Neměň fakta.
666
-
667
- VSTUPNÍ PŘEPIS:
668
  ---
669
  {raw_transcript}
670
  ---
671
- POŽADOVANÝ VÝSTUP (pouze čistý text v ČEŠTINĚ, rozdělený do logických odstavců):"""
672
- edit_system_message="Jsi AI editor specializovaný na převod surového přepisu do čistého, editovaného českého textu. Pracuješ precizně a dodržuješ všechna pravidla."
673
  edited_transcript_for_state = call_gpt(edit_prompt, system_message=edit_system_message)
 
 
674
 
675
- if edited_transcript_for_state.startswith("Chyba:") or not edited_transcript_for_state or not edited_transcript_for_state.strip():
676
- raise Exception(f"Chyba editace GPT nebo prázdný výstup: {edited_transcript_for_state}")
677
- print("Editing OK.")
678
- gr.Info("Úprava textu dokončena.")
679
- formatted_transcript_w_chapters = edited_transcript_for_state # Default display value before adding chapters
680
-
681
- # --- ESTIMATE DURATION IF NO SEGMENTS ---
682
- if not segments and raw_transcript:
683
- # Simple estimate: ~150 words per minute = 2.5 words per second
684
- word_count = len(raw_transcript.split())
685
- estimated_duration_override = max(60, word_count / 2.5) # Ensure minimum estimate (e.g., 1 min)
686
- print(f"Odhaduji délku audia z textu ({word_count} slov): {estimated_duration_override:.0f}s (pro účely formátování)")
687
- elif segments:
688
- estimated_duration_override = audio_duration # Use duration from Whisper if available
689
-
690
- # --- CHAPTERS (Uses edited_transcript_for_state) ---
691
  progress(0.5, desc=f"Generování kapitol ({GPT_MODEL})...")
692
- parsed_chapters_list = []
693
- chapters_formatted = "Kapitoly nebyly vygenerovány."
694
- # Generate chapters even without segments, GPT analyzes the text
695
- print("Generating chapters (analyzing edited text)...");
696
- gr.Info("Generuji návrhy kapitol...")
697
- # Estimate number of chapters based on text length instead of audio duration if needed
698
- text_length_chars = len(edited_transcript_for_state)
699
- if text_length_chars < 2000: num_chapters = random.randint(1, 3) # Very short text
700
- elif text_length_chars < 10000: num_chapters = random.randint(3, 5) # Short text
701
- elif text_length_chars < 50000: num_chapters = random.randint(5, 8) # Medium
702
- elif text_length_chars < 150000: num_chapters = random.randint(7, 10) # Long text
703
- else: num_chapters = random.randint(9, 12) # Very long text
704
- print(f"Requesting ~{num_chapters} chapters based on text length ({text_length_chars} chars)...")
705
  try:
706
- # Chapter prompt - use the full edited transcript
707
- chapter_prompt = f"""Analyzuj následující text v ČEŠTINĚ a vygeneruj přibližně {num_chapters} relevantních kapitol pro YouTube (může být méně, pokud text není dostatečně členitý, ale alespoň 1, pokud text dává smysl).
708
 
709
- Kontext (nepovinné, pro lepší pochopení témat):
710
- {context_for_state}
711
 
712
  VSTUPNÍ TEXT K ANALÝZE (ČEŠTINA):
713
  ---
@@ -715,56 +409,49 @@ VSTUPNÍ TEXT K ANALÝZE (ČEŠTINA):
715
  ---
716
 
717
  Instrukce pro generování kapitol:
718
- 1. Pečlivě identifikuj hlavní témata nebo logické předěly v textu. Každá kapitola by měla pokrývat smysluplný úsek.
719
- 2. Pro každé téma odhadni čas začátku ve formátu HH:MM:SS (nebo MM:SS pro časy pod hodinu). Čas odhadni na základě pozice tématu v celkovém textu (např. téma v polovině textu by mělo mít čas zhruba v polovině odhadované celkové délky). První kapitola MUSÍ začínat 00:00:00 (nebo 00:00).
720
- 3. Vytvoř krátký, výstižný název tématu v ČEŠTINĚ (ideálně max 5-7 slov). Název by měl jasně říkat, o čem daný úsek je.
721
  4. Naformátuj každou kapitolu PŘESNĚ jako: HH:MM:SS - Název tématu (nebo MM:SS - Název tématu). Každá kapitola na novém řádku.
722
- 5. Seřaď kapitoly chronologicky podle odhadovaného času.
723
 
724
- POŽADOVANÝ VÝSTUP: Vrať POUZE seznam kapitol ve výše uvedeném formátu, každou na novém řádku. Pokud nenajdeš žádné smysluplné kapitoly (např. text je příliš krátký nebo nesouvislý), vrať POUZE text "ŽÁDNÉ KAPITOLY". Nepřidávej žádné další komentáře, vysvětlivky, úvody ani pozdravy."""
725
- chapter_system_message="Jsi AI asistent, který striktně generuje POUZE seznam YouTube kapitol ve formátu 'HH:MM:SS - Název' nebo 'MM:SS - Název', nebo text 'ŽÁDNÉ KAPITOLY'."
726
  chapters_raw = call_gpt(chapter_prompt, system_message=chapter_system_message)
727
  print(f"Raw Chapters Output from GPT:\n---\n{chapters_raw}\n---")
728
  if not chapters_raw.startswith("Chyba:") and "ŽÁDNÉ KAPITOLY" not in chapters_raw and chapters_raw.strip():
729
- parsed_chapters_list = parse_chapters(chapters_raw) # This function parses the text format
730
- if parsed_chapters_list:
731
- # Ensure first chapter starts at 0 if parsing didn't force it
732
- if parsed_chapters_list[0]['time'] != 0:
733
- print("Adjusting first chapter time to 00:00.")
734
- parsed_chapters_list[0]['time'] = 0
735
- chapters_formatted_list = [f"{format_yt_timestamp(ch['time'])} - {ch['title']}" for ch in parsed_chapters_list]
736
- chapters_formatted = "\n".join(chapters_formatted_list)
737
- print("Chapters OK.")
738
- gr.Info("Návrhy kapitol vygenerovány.")
739
- else:
740
- chapters_formatted = "Kapitoly vygenerovány GPT, ale nepodařilo se rozpoznat jejich formát."
741
- print("Chapter parsing failed despite GPT generating output.")
742
- gr.Warning(chapters_formatted)
743
- elif "ŽÁDNÉ KAPITOLY" in chapters_raw:
744
- chapters_formatted = "Pro tento text nebyly nalezeny žádné smysluplné kapitoly."
745
- print("GPT indicated no chapters found.")
746
- gr.Info(chapters_formatted)
747
- else:
748
- chapters_formatted = chapters_raw if chapters_raw.startswith("Chyba:") else "Generování kapitol selhalo nebo vrátilo prázdný výstup."
749
- print(f"Chapter generation failed or returned empty: {chapters_formatted}")
750
- gr.Warning(chapters_formatted)
751
- except Exception as e:
752
- chapters_formatted = f"Chyba při generování kapitol: {e}"
753
- print(chapters_formatted); traceback.print_exc()
754
- gr.Error(chapters_formatted)
755
-
756
- # --- REELS (Uses edited_transcript_for_state) ---
757
  progress(0.7, desc=f"Generování Reels ({GPT_MODEL})...")
758
- reels_suggestions = "Návrhy pro Reels nebyly vygenerovány."
 
759
  if edited_transcript_for_state and not edited_transcript_for_state.startswith("Chyba:"):
760
- print("Generating Reels suggestions (analyzing edited text)...")
761
- gr.Info("Generuji návrhy na Reels/TikTok...")
762
  try:
763
- # Reels prompt - uses full edited transcript
764
- reels_prompt = f"""Analyzuj následující text v ČEŠTINĚ a identifikuj 3-5 krátkých (cca 15-45 sekund), velmi zajímavých a samostatně stojících úseků, vhodných pro krátká videa jako Reels/TikTok. Hledej silné výroky, emoce, klíčové momenty, překvapivé informace nebo praktické tipy.
765
 
766
- Kontext (nepovinné, pro lepší pochopení významu):
767
- {context_for_state}
768
 
769
  VSTUPNÍ TEXT K ANALÝZE (ČEŠTINA):
770
  ---
@@ -772,237 +459,169 @@ VSTUPNÍ TEXT K ANALÝZE (ČEŠTINA):
772
  ---
773
 
774
  Instrukce pro každý návrh:
775
- 1. Odhadni čas začátku a konce úseku ve formátu HH:MM:SS.ms - HH:MM:SS.ms (nebo MM:SS.ms). Čas odhadni podle pozice v textu a odhadované celkové délky. Časy by měly být konzistentní s kapitolami, pokud byly generovány.
776
- 2. Napiš stručný, lákavý popis obsahu úseku (1-2 věty v ČEŠTINĚ).
777
- 3. Vyber krátkou, údernou citaci/frázi přímo z daného úseku textu (v ČEŠTINĚ, v uvozovkách).
778
 
779
- POŽADOVANÝ VÝSTUP: Vrať POUZE seznam návrhů ve formátu níže, oddělených prázdným řádkem. Pokud nenajdeš žádné vhodné úseky, vrať POUZE text "ŽÁDNÉ NÁVRHY". Nepřidávej žádné další komentáře, úvody ani text.
780
 
781
  Formát pro každý návrh:
782
  Čas: HH:MM:SS.ms - HH:MM:SS.ms
783
  Popis: [Stručný popis]
784
  Citace: „[Přesná citace z textu]“"""
785
- reels_system_message="Jsi AI asistent, který striktně generuje POUZE seznam návrhů pro Reels v požadovaném formátu ('Čas: ...\nPopis: ...\nCitace: ...') nebo text 'ŽÁDNÉ NÁVRHY'."
786
  reels_result = call_gpt(reels_prompt, system_message=reels_system_message)
787
  print(f"Raw Reels Output from GPT:\n---\n{reels_result}\n---")
788
- # Check if the output looks like valid suggestions
789
  if not reels_result.startswith("Chyba:") and "ŽÁDNÉ NÁVRHY" not in reels_result and "Čas:" in reels_result and "Popis:" in reels_result and "Citace:" in reels_result :
790
- reels_suggestions = reels_result
791
- print("Reels OK.")
792
- gr.Info("Návrhy na Reels vygenerovány.")
 
 
793
  elif "ŽÁDNÉ NÁVRHY" in reels_result:
794
- reels_suggestions = "Nebyly nalezeny žádné vhodné úseky pro Reels."
795
- print("GPT indicated no Reels suggestions found.")
796
- gr.Info(reels_suggestions)
797
  else:
798
- reels_suggestions = reels_result if reels_result.startswith("Chyba:") else "Generování Reels selhalo nebo vrátilo neočekávaný formát."
799
- print(f"Reels output unexpected or error: {reels_result[:200]}...")
800
- gr.Warning(reels_suggestions)
801
- except Exception as e:
802
- reels_suggestions = f"Chyba při generování Reels: {e}"
803
- print(reels_suggestions); traceback.print_exc()
804
- gr.Error(reels_suggestions)
805
- else:
806
- reels_suggestions = "Nelze generovat Reels (chybí platný editovaný přepis)."
807
- print(reels_suggestions)
808
 
 
 
 
809
 
810
- # --- FORMAT TRANSCRIPT WITH CHAPTERS (if chapters parsed) ---
811
  progress(0.9, desc="Formátování výstupu...")
812
- if parsed_chapters_list and edited_transcript_for_state and not edited_transcript_for_state.startswith("Chyba:"):
 
813
  print("Formatting transcript with generated chapters...")
814
- # Pass the estimated duration if available
815
- formatted_transcript_w_chapters = format_transcript_with_chapters(
816
- edited_transcript_for_state,
817
- parsed_chapters_list,
818
- audio_duration_estimate=estimated_duration_override # Use estimate or actual duration
819
- )
820
  print("Formatted transcript with chapters prepared.")
821
  elif edited_transcript_for_state and not edited_transcript_for_state.startswith("Chyba:"):
822
- # If chapters failed or weren't found, just use the edited transcript
823
- formatted_transcript_w_chapters = edited_transcript_for_state
824
- print("Chapters not available or failed, displaying edited transcript without chapter headings.")
825
  else:
826
- # If editing failed, keep the error message
827
- formatted_transcript_w_chapters = edited_transcript_for_state
828
- print("Editing failed, cannot format transcript.")
829
-
830
-
831
- progress(1.0, desc="Hotovo!"); print(f"Processing OK (Source: {input_source}).")
832
- gr.Info("Zpracování dokončeno.")
833
- # Return values - make sure segments is returned (it will be [] if transcript was provided)
834
- # Ensure chapters_formatted and reels_suggestions reflect the final status/error messages
835
- return formatted_transcript_w_chapters, chapters_formatted, reels_suggestions, edited_transcript_for_state, context_for_state, segments, chapters_formatted, reels_suggestions
836
-
837
- except ValueError as ve: # Catch specific input errors (e.g., file too big, empty input)
838
- error_message = f"Chyba vstupu: {ve}"
839
- print(error_message)
840
- gr.Error(error_message) # Show error in Gradio UI
841
- # Return empty values for all outputs on input error to clear UI
842
- return "", "", "", "", "", [], "", ""
843
- except Exception as e:
844
- error_message = f"Neočekávaná chyba během zpracování: {e}"
845
- print(error_message); traceback.print_exc()
846
- gr.Error(error_message) # Show general error in Gradio UI
847
- # Return error message in the first field, empty others
848
- # Keep potentially generated context/segments if error happened later
849
- return error_message, chapters_formatted, reels_suggestions, edited_transcript_for_state, context_for_state, segments, chapters_formatted, reels_suggestions
850
 
851
 
852
  # --- Gradio Interface Definition ---
853
  theme = gr.themes.Default(primary_hue=gr.themes.colors.blue, secondary_hue=gr.themes.colors.sky)
854
 
855
- # --- Build Gradio UI ---
856
- with gr.Blocks(theme=theme, title="WhisperBitch v2") as demo:
857
- # <<< CHANGE: Updated Titles and Info Text >>>
858
- gr.Markdown("# 🧠 WhisperBitch v2 (s podporou vložení přepisu)", elem_id="app-title")
859
- gr.Markdown("Nástroj pro automatický přepis, editaci, překlad, generování kapitol, Reels a návrhů článků z audia nebo textu.", elem_id="app-subtitle")
860
- gr.Markdown("Nahrajte audio (limit ~25MB), vložte text přepisu, nebo nahrajte .txt soubor. Zpracování může trvat několik minut.", elem_id="time-info")
861
-
862
- # --- State variables --- (remain the same)
863
- transcript_state = gr.State(value="") # Stores the final edited transcript (Czech)
864
- context_state = gr.State(value="") # Stores the context string
865
- segments_state = gr.State(value=[]) # Stores raw segments from Whisper (for SRT/VTT), empty if text input
866
- chapters_state = gr.State(value="") # Stores the formatted chapters string for ZIP
867
- reels_state = gr.State(value="") # Stores the formatted reels string for ZIP
868
- article_state = gr.State(value="") # Stores the generated article string
869
- srt_path_state = gr.State(value=None) # Stores the temporary path of the generated SRT file
870
- vtt_path_state = gr.State(value=None) # Stores the temporary path of the generated VTT file
871
 
872
  # --- UI Layout ---
873
  with gr.Row():
874
  # --- Input Column ---
875
  with gr.Column(scale=1, min_width=350):
876
- gr.Markdown("### 1. Zadejte Vstup")
877
  with gr.Tabs():
878
  with gr.TabItem("🎤 Audio"):
879
- audio_input = gr.Audio(type="filepath", label="Nahrát audio soubor (max ~25MB)", sources=["upload", "microphone"])
880
- with gr.TabItem("📝 Text"):
881
- transcript_text_input = gr.Textbox(
882
- label="Vložit surový přepis",
883
- placeholder="Vložte nebo napište zde text přepisu (CZ, SK, EN...). Bude upraven a přeložen do CZ.",
884
- lines=10,
885
- info="Pokud toto pole vyplníte, ostatní vstupy budou ignorovány."
886
- )
887
- with gr.TabItem("📂 Soubor"):
888
- transcript_file_input = gr.File(
889
- label="Nahrát soubor s přepisem (.txt)",
890
- file_types=[".txt"],
891
- )
892
-
893
  gr.Markdown("### 2. Kontext (nepovinné)")
894
- description_input = gr.Textbox(label="Popis / Téma nahrávky", placeholder="Např. Rozhovor s expertem na AI o budoucnosti práce.", lines=3)
895
- keywords_input = gr.Textbox(label="Klíčová slova (oddělená čárkou)", placeholder="AI, automatizace, budoucnost práce, podcast...", lines=3)
896
-
897
  submit_button = gr.Button("🚀 Zpracovat Vstup", variant="primary", elem_id="submit-button")
898
 
899
  # --- Output Column ---
900
  with gr.Column(scale=2, min_width=600):
901
- gr.Markdown("### 3. Výstupy Zpracování")
 
902
  edited_output_formatted = gr.Textbox(label="✅ Upravený přepis s kapitolami (CZ)", lines=15, interactive=False, show_copy_button=True)
903
  with gr.Row():
 
904
  chapters_output = gr.Textbox(label="🎬 Kapitoly pro YouTube (CZ)", lines=7, interactive=False, show_copy_button=True, scale=1)
905
  reels_output = gr.Textbox(label="🎬 Reels / TikTok návrhy (CZ)", lines=7, interactive=False, show_copy_button=True, scale=1)
906
 
907
- # --- Optional Accordions ---
908
- with gr.Accordion("📰 Generování článku (volitelné)", open=False) as acc_article:
909
- article_extra_prompt_input = gr.Textbox(label="⭐ Extra pokyny pro článek (nepovinné)", placeholder="Např. Zaměř se více na praktické dopady, cíl na manažery...", lines=2)
 
910
  generate_article_button = gr.Button("✍️ Vygenerovat článek", variant="secondary")
911
  article_output_display = gr.Textbox(label="Článek (návrh v CZ)", lines=20, interactive=False, show_copy_button=True)
912
 
913
- with gr.Accordion("📺 Generování titulků (volitelné)", open=False) as acc_subs:
914
- # <<< CHANGE: Added warning about needing audio input >>>
915
- gr.Markdown("⚠️ Titulky (SRT/VTT) lze generovat **pouze** při zpracování **audio souboru**, protože vyžadují přesné časové značky segmentů z přepisu.", elem_id="subs-warning")
916
  with gr.Row():
917
  generate_srt_button = gr.Button("Generovat .SRT", variant="secondary")
918
  generate_vtt_button = gr.Button("Generovat .VTT", variant="secondary")
919
  with gr.Row():
920
- srt_output_ondemand = gr.File(label="SRT Titulky ke stažení", interactive=False) # File output for direct download
921
- vtt_output_ondemand = gr.File(label="VTT Titulky ke stažení", interactive=False) # File output for direct download
922
 
923
  # --- Download Button ---
924
  gr.Markdown("### 4. Stažení")
925
  download_button = gr.Button("⬇️ Stáhnout vše (.zip)", variant="primary")
926
- download_file_output = gr.File(label="ZIP Archiv ke stažení", interactive=False) # Keep visible, maybe hide initially?
927
 
928
  # --- Event Handling ---
929
-
930
- # <<< CHANGE: Updated inputs for process_audio >>>
931
  submit_button.click(
932
- fn=process_audio,
933
- inputs=[
934
- audio_input,
935
- description_input,
936
- keywords_input,
937
- transcript_text_input, # Added
938
- transcript_file_input # Added
939
- ],
940
  outputs=[
941
- edited_output_formatted, # Textbox: Upravený přepis s kapitolami (CZ)
942
- chapters_output, # Textbox: Kapitoly pro YouTube (CZ)
943
- reels_output, # Textbox: Reels / TikTok návrhy (CZ)
944
- transcript_state, # State: Stores edited transcript
945
- context_state, # State: Stores context
946
- segments_state, # State: Stores segments (will be [] if text input)
947
- chapters_state, # State: Stores formatted chapters for ZIP
948
- reels_state # State: Stores formatted reels for ZIP
949
  ],
950
- # Show progress animation
951
  show_progress="full"
952
  )
953
 
954
- # Generate Article Button
955
- generate_article_button.click(
956
- fn=generate_article_content,
957
- inputs=[transcript_state, context_state, article_extra_prompt_input],
958
- outputs=[article_output_display, article_state], # Update display and state
959
- show_progress="full"
960
- )
961
-
962
- # Generate SRT Button
963
- generate_srt_button.click(
964
- fn=generate_srt_file,
965
- inputs=[segments_state],
966
- outputs=[srt_output_ondemand, srt_path_state], # Update file component and state path
967
- show_progress="minimal"
968
- )
969
-
970
- # Generate VTT Button
971
- generate_vtt_button.click(
972
- fn=generate_vtt_file,
973
- inputs=[segments_state],
974
- outputs=[vtt_output_ondemand, vtt_path_state], # Update file component and state path
975
- show_progress="minimal"
976
- )
977
-
978
- # Download All Button
979
  download_button.click(
980
  fn=create_download_zip,
981
  inputs=[
982
- transcript_state,
983
  chapters_state,
984
  reels_state,
985
- srt_path_state, # Use the path stored in state
986
- vtt_path_state, # Use the path stored in state
987
  article_state
988
  ],
989
- outputs=[download_file_output], # Output to the final download file component
990
  show_progress="minimal"
991
  )
992
 
993
  # --- Launch ---
994
  if __name__ == "__main__":
995
- # <<< CHANGE: Check for client initialization before launch >>>
996
- if not client:
997
- print("\n" + "="*60)
998
- print("!!! KRITICKÁ CHYBA: OpenAI klient není inicializován !!!")
999
- print("!!! GPT funkce (editace, kapitoly, reels, článek) nebudou fungovat. !!!")
1000
- print("!!! Ujistěte se, že máte správně nastavenou proměnnou prostředí OPENAI_API_KEY. !!!")
1001
- print("="*60 + "\n")
1002
- # Optional: Exit if client is crucial and not set?
1003
- # sys.exit("Exiting due to missing OpenAI client.")
1004
- else:
1005
- print("\nOpenAI client looks OK. Starting Gradio...")
1006
-
1007
- # Set share=True if you want a public link (useful for testing)
1008
  demo.launch(share=False)
 
6
  import tempfile
7
  import traceback
8
  import math
9
+ import re # Keep re for parsing chapters and sanitizing filenames
 
10
  import zipfile
11
  import shutil
12
+ import json
13
 
14
  # --- Configuration & OpenAI Client Setup ---
15
  OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
16
  WHISPER_MODEL = "whisper-1"
 
17
  GPT_MODEL = "gpt-4.1"
18
  client = None
19
  if OPENAI_API_KEY:
 
27
 
28
  # --- Helper Functions ---
29
 
30
+ # format_timestamp, format_yt_timestamp remain the same
31
  def format_timestamp(seconds, format_type='srt', precision='milliseconds'):
32
+ if not isinstance(seconds, (int, float)) or seconds < 0: seconds = 0
33
+ seconds_int = int(seconds); milliseconds_part = seconds - seconds_int; milliseconds = int(milliseconds_part * 1000)
34
+ td = datetime.timedelta(seconds=seconds_int); total_seconds = int(td.total_seconds())
35
+ hours, remainder = divmod(total_seconds, 3600); minutes, seconds_rem = divmod(remainder, 60)
36
+ if precision == 'seconds': return f"{hours:02}:{minutes:02}:{seconds_rem:02}"
37
+ else: separator = ',' if format_type == 'srt' else '.'; return f"{hours:02}:{minutes:02}:{seconds_rem:02}{separator}{milliseconds:03}"
 
 
 
 
 
 
 
 
 
 
38
 
39
  def format_yt_timestamp(seconds):
40
+ if not isinstance(seconds, (int, float)) or seconds < 0: seconds = 0
41
+ td = datetime.timedelta(seconds=int(seconds)); total_seconds = int(td.total_seconds())
42
+ hours, remainder = divmod(total_seconds, 3600); minutes, seconds_rem = divmod(remainder, 60)
43
+ if hours > 0: return f"{hours}:{minutes:02}:{seconds_rem:02}"
44
+ else: return f"{minutes:02}:{seconds_rem:02}"
 
 
 
 
 
 
45
 
46
+ # <<< RESTORED: parse_chapters to handle GPT's timed output >>>
47
  def parse_chapters(chapter_text):
48
  """Parses chapter text (HH:MM:SS - Title) into a list of dictionaries."""
49
  chapters = []
 
50
  pattern = re.compile(r"^(?:(\d{1,2}):)?(\d{1,2}):(\d{2})\s*-\s*(.+)$", re.MULTILINE)
51
+ if not chapter_text: return chapters
52
+ print(f"Parsing chapter text from GPT:\n---\n{chapter_text}\n---")
 
53
  for match in pattern.finditer(chapter_text):
54
  try:
55
+ hours_str = match.group(1); minutes_str = match.group(2); seconds_str = match.group(3); title = match.group(4).strip()
56
+ hours = int(hours_str) if hours_str else 0; minutes = int(minutes_str) if minutes_str else 0; seconds = int(seconds_str) if seconds_str else 0
57
+ if not (0 <= minutes < 60 and 0 <= seconds < 60): print(f"Skipping invalid time in chapter: '{match.group(0)}'"); continue
 
 
 
 
 
 
 
 
 
 
 
58
  total_seconds = hours * 3600 + minutes * 60 + seconds
59
  chapters.append({"time": total_seconds, "title": title})
60
+ except Exception as e: print(f"Error parsing chapter line: '{match.group(0)}' - {e}")
61
+ try: chapters.sort(key=lambda x: x['time'])
62
+ except Exception as e: print(f"Error sorting chapters: {e}")
63
+ print(f"Parsed chapters from GPT: {chapters}")
 
 
 
 
 
 
64
  return chapters
65
 
66
+ # <<< RESTORED: format_transcript_with_chapters to insert timed chapters >>>
67
+ def format_transcript_with_chapters(edited_transcript, parsed_chapters, audio_duration):
68
+ """Formats transcript with chapter headings using known audio duration."""
69
+ if not parsed_chapters or not edited_transcript or audio_duration <= 0: return edited_transcript
70
  output_parts = []; last_char_pos = 0; total_len = len(edited_transcript)
71
+ print(f"Formatting transcript with chapters using actual duration: {audio_duration:.0f}s")
72
 
 
 
 
 
 
 
 
 
73
  for i, chapter in enumerate(parsed_chapters):
74
+ # Use the time from the parsed chapter generated by GPT
75
+ chapter_time = chapter.get('time', 0)
76
+ # Estimate position based on GPT's time relative to total duration
77
+ approx_char_pos = int((chapter_time / audio_duration) * total_len) if audio_duration > 0 else 0
78
+
79
+ # Heuristic to find a nearby newline (same logic as before)
80
  search_window_start = max(last_char_pos, approx_char_pos - min(300, (approx_char_pos - last_char_pos) // 2 if (approx_char_pos - last_char_pos) > 0 else 100))
81
  insert_pos = edited_transcript.rfind('\n', search_window_start, approx_char_pos)
 
82
  if insert_pos == -1 or insert_pos < last_char_pos:
 
83
  insert_pos = edited_transcript.find('\n', approx_char_pos, approx_char_pos + 100)
84
+ if insert_pos == -1:
 
85
  space_pos = edited_transcript.rfind(' ', search_window_start, approx_char_pos)
86
+ insert_pos = space_pos + 1 if space_pos != -1 and space_pos > last_char_pos else approx_char_pos
87
+ else: insert_pos += 1
88
+ else: insert_pos += 1
 
 
 
 
 
 
 
89
  insert_pos = min(max(last_char_pos, insert_pos), total_len)
90
 
91
  output_parts.append(edited_transcript[last_char_pos:insert_pos])
 
92
  heading_prefix = "\n\n" if insert_pos > 0 else ""
93
+ # Use the time from the chapter dict, format it
94
+ heading = f"{heading_prefix}({format_timestamp(chapter_time, precision='seconds')} - {chapter['title']})\n"
95
+ output_parts.append(heading); last_char_pos = insert_pos
96
 
97
  output_parts.append(edited_transcript[last_char_pos:])
98
  result = "".join(output_parts).strip()
99
+ print("Transcript formatting with chapters complete.")
100
  return result
101
 
102
+ # parse_specific_timecode remains the same
103
+ def parse_specific_timecode(tc_str):
104
+ tc_str = tc_str.strip(); match = re.match(r'(\d{2}):(\d{2}):(\d{2}),(\d{3})', tc_str)
105
+ if match:
106
+ h, m, s, ms = map(int, match.groups())
107
+ if not (0 <= m < 60 and 0 <= s < 60 and 0 <= ms < 1000): raise ValueError(f"Invalid time values: {tc_str}")
108
+ return float(h * 3600 + m * 60 + s + ms / 1000.0)
109
+ else:
110
+ match = re.match(r'(\d{2}):(\d{2}),(\d{3})', tc_str) # Try MM:SS,ms
111
+ if match:
112
+ m, s, ms = map(int, match.groups())
113
+ if not (0 <= m < 60 and 0 <= s < 60 and 0 <= ms < 1000): raise ValueError(f"Invalid time values: {tc_str}")
114
+ return float(m * 60 + s + ms / 1000.0)
115
+ else: raise ValueError(f"Unknown timecode format: {tc_str}. Expected HH:MM:SS,ms or MM:SS,ms")
116
+
117
+ # format_srt, format_vtt remain the same
118
  def format_srt(segments):
119
+ srt_content = "" # ... (implementation remains the same) ...
120
+ if not segments or not isinstance(segments, list): return ""
121
+ segment_count = 0
122
+ for i, segment_data in enumerate(segments):
123
+ if not isinstance(segment_data, dict) or not all(key in segment_data for key in ['start', 'end', 'text']): print(f"SRT segment {i} invalid structure"); continue
124
+ try: start_s = float(segment_data['start']); end_s = float(segment_data['end']); text = str(segment_data['text']).strip() if segment_data['text'] is not None else ""
125
+ except (ValueError, TypeError) as e: print(f"SRT segment {i} invalid time/text type: {e}"); continue
126
+ if start_s < 0 or end_s < start_s: print(f"SRT segment {i} invalid times: {start_s}-{end_s}"); continue
127
+ start_time = format_timestamp(start_s, 'srt'); end_time = format_timestamp(end_s, 'srt')
128
+ max_length = 42; words = text.split(); lines = []; current_line = ""
129
+ for word in words:
130
+ if not current_line: current_line = word
131
+ elif len(current_line) + len(word) + 1 <= max_length: current_line += " " + word
132
+ else: lines.append(current_line); current_line = word
133
+ if current_line: lines.append(current_line)
134
+ formatted_text = "\n".join(l for l in lines if l)
135
+ if formatted_text: segment_count += 1; srt_content += f"{segment_count}\n{start_time} --> {end_time}\n{formatted_text}\n\n"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
136
  return srt_content
137
 
138
  def format_vtt(segments):
139
+ vtt_content = "WEBVTT\n\n" # ... (implementation remains the same) ...
140
+ if not segments or not isinstance(segments, list): return vtt_content
141
+ for i, segment_data in enumerate(segments):
142
+ if not isinstance(segment_data, dict) or not all(key in segment_data for key in ['start', 'end', 'text']): print(f"VTT segment {i} invalid structure"); continue
143
+ try: start_s = float(segment_data['start']); end_s = float(segment_data['end']); text = str(segment_data['text']).strip() if segment_data['text'] is not None else ""
144
+ except (ValueError, TypeError) as e: print(f"VTT segment {i} invalid time/text type: {e}"); continue
145
+ if start_s < 0 or end_s < start_s: print(f"VTT segment {i} invalid times: {start_s}-{end_s}"); continue
146
+ start_time = format_timestamp(start_s, 'vtt'); end_time = format_timestamp(end_s, 'vtt')
147
+ max_length = 42; words = text.split(); lines = []; current_line = ""
148
+ for word in words:
149
+ if not current_line: current_line = word
150
+ elif len(current_line) + len(word) + 1 <= max_length: current_line += " " + word
151
+ else: lines.append(current_line); current_line = word
152
+ if current_line: lines.append(current_line)
153
+ formatted_text = "\n".join(l for l in lines if l)
154
+ if formatted_text: vtt_content += f"{start_time} --> {end_time}\n{formatted_text}\n\n"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
155
  return vtt_content
156
 
157
+ # call_gpt remains the same
158
  def call_gpt(prompt, system_message="Jsi užitečný AI asistent."):
159
+ # ... (implementation remains the same) ...
160
+ if not client: print("Error: OpenAI client not initialized."); return "Chyba: OpenAI klient není inicializován."
 
 
161
  try:
162
+ print(f"Calling GPT Model: {GPT_MODEL}..."); response = client.chat.completions.create(model=GPT_MODEL, messages=[ {"role": "system", "content": system_message}, {"role": "user", "content": prompt} ])
163
+ result = response.choices[0].message.content.strip(); print("GPT Call OK.")
164
+ if not result or len(result) < 5: print(f"Warning: GPT returned potentially empty/short response: '{result}'") # Adjusted length check slightly
 
 
 
 
 
 
 
 
 
 
 
 
165
  return result
166
+ except openai.NotFoundError as e: print(f"GPT Error: Model '{GPT_MODEL}' not found..."); return f"Chyba GPT: Model '{GPT_MODEL}' nenalezen..."
167
+ except openai.RateLimitError as e: print(f"GPT Error: Rate limit exceeded."); return f"Chyba GPT: Překročen limit požadavků..."
168
+ except openai.APIConnectionError as e: print(f"GPT Error: Network issue."); return f"Chyba GPT: Problém s připojením..."
169
+ except Exception as e: print(f"An unexpected GPT Error occurred: {e}"); traceback.print_exc(); return f"Chyba GPT: Neočekávaná chyba - {e}"
170
+
 
 
 
 
 
 
 
 
 
 
 
171
 
172
+ # generate_article_content remains the same
173
  def generate_article_content(transcript_state, context_state, article_extra_prompt, progress=gr.Progress(track_tqdm=True)):
174
+ # ... (implementation remains the same) ...
175
  article_result = "Chyba: Generování článku selhalo."
176
  try:
177
  print("--- generate_article_content called ---")
178
+ if not transcript_state or transcript_state.startswith("Chyba:"): return "Chyba: Nelze generovat článek bez platného přepisu.", "Chyba: Nelze generovat článek bez platného přepisu."
179
+ if not client: return "Chyba: OpenAI klient není inicializován.", "Chyba: OpenAI klient není inicializován."
 
 
 
180
  progress(0.1, desc="Příprava na generování článku..."); print("Generating article...")
181
+ word_count = len(str(transcript_state).split()); is_long_article = word_count > 400
182
+ article_prompt = f"""POKYN: Jsi AI redaktor... (celý prompt pro článek) ...
 
 
 
 
 
 
 
183
 
184
  == VSTUP: Editovaný přepis ==
185
  --- START ---
186
  {transcript_state}
187
  --- END ---
188
+ ... (zbytek promptu) ..."""
189
+ system_msg = "Tvojí jedinou rolí je generovat strukturovaný textový výstup v češtině..."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
190
  progress(0.5, desc=f"Volání GPT ({GPT_MODEL})...");
191
  article_result = call_gpt(article_prompt, system_message=system_msg)
192
+ if article_result.startswith("Chyba GPT:") or not article_result or len(article_result) < 100: raise Exception(f"Generování článku selhalo: {article_result}")
 
 
 
193
  progress(1.0, desc="Článek vygenerován."); print("Article generation OK.")
194
+ 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
 
 
 
 
 
 
195
  print(f"--- generate_article_content finished, returning result starting with: {str(article_result)[:150]}...")
 
196
  return article_result, article_result
197
 
198
+
199
+ # generate_srt_file / generate_vtt_file remain the same
200
  def generate_srt_file(segments_state):
201
+ # ... (implementation remains the same) ...
202
+ if not segments_state or not isinstance(segments_state, list) or len(segments_state) == 0: gr.Warning("Nelze generovat SRT - chybí data segmentů."); return None, None
203
+ print("Generating SRT file..."); srt_content = format_srt(segments_state)
204
+ if not srt_content: gr.Warning("Nepodařilo se vygenerovat obsah SRT."); return None, None
 
 
 
 
 
205
  try:
206
+ with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.srt', encoding='utf-8', prefix='sub_') as f: f.write(srt_content); srt_filepath = f.name
207
+ print(f"SRT file generated: {srt_filepath}"); return srt_filepath, srt_filepath
208
+ except Exception as e: error_msg = f"Chyba zápisu SRT: {e}"; print(error_msg); traceback.print_exc(); gr.Error(error_msg); return None, None
 
 
 
 
 
 
 
 
 
 
209
 
210
  def generate_vtt_file(segments_state):
211
+ # ... (implementation remains the same) ...
212
+ if not segments_state or not isinstance(segments_state, list) or len(segments_state) == 0: gr.Warning("Nelze generovat VTT - chybí data segmentů."); return None, None
213
+ print("Generating VTT file..."); vtt_content = format_vtt(segments_state)
214
+ if not vtt_content or vtt_content.strip() == "WEBVTT": gr.Warning("Nepodařilo se vygenerovat obsah VTT."); return None, None
 
 
 
 
 
 
215
  try:
216
+ with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.vtt', encoding='utf-8', prefix='sub_') as f: f.write(vtt_content); vtt_filepath = f.name
217
+ print(f"VTT file generated: {vtt_filepath}"); return vtt_filepath, vtt_filepath
218
+ except Exception as e: error_msg = f"Chyba zápisu VTT: {e}"; print(error_msg); traceback.print_exc(); gr.Error(error_msg); return None, None
 
 
 
 
 
 
 
 
 
 
219
 
220
+ # <<< CHANGE: create_download_zip restored chapter/reels timed format assumption >>>
221
+ def create_download_zip(transcript_formatted, chapters_timed, reels_timed, srt_path, vtt_path, article):
222
  """Creates a ZIP file containing all generated outputs."""
223
  print("Attempting to create ZIP file...")
 
224
  final_zip_path = None
225
+ base_filename = "prepisovac_vystupy"
226
 
 
227
  if article and isinstance(article, str) and not article.startswith("Chyba:"):
228
+ # ... (extract title logic remains the same) ...
229
  title_match = re.search(r"Popisný:\s*\n(.+)", article, re.IGNORECASE)
230
+ if not title_match: title_match = re.search(r"Návrhy titulků:\s*\n(?:.+\:\s*\n)?(.+)", article, re.IGNORECASE)
 
 
231
  if title_match:
232
+ extracted_title = title_match.group(1).strip(); sanitized_title = re.sub(r'[\\/*?:"<>|]', "", extracted_title); sanitized_title = re.sub(r'\s+', '_', sanitized_title); base_filename = sanitized_title[:50]
 
 
 
 
233
  print(f"Using base filename from article title: '{base_filename}'")
234
+ else: print("Could not extract title from article, using default filename.")
 
235
 
236
  try:
 
237
  with tempfile.TemporaryDirectory() as temp_dir:
238
+ zip_filename = f"{base_filename}.zip"; zip_filepath = os.path.join(temp_dir, zip_filename)
 
239
  print(f"Creating zip archive at: {zip_filepath}")
 
240
  files_added_count = 0
241
  with zipfile.ZipFile(zip_filepath, 'w', zipfile.ZIP_DEFLATED) as zipf:
242
+ # Add Formatted Transcript (with chapters inserted if available)
243
+ if transcript_formatted and isinstance(transcript_formatted, str) and not transcript_formatted.startswith("Chyba:"):
244
+ t_filename = "prepis_s_kapitolami.txt"; t_filepath = os.path.join(temp_dir, t_filename)
245
+ with open(t_filepath, 'w', encoding='utf-8') as f: f.write(transcript_formatted)
246
+ zipf.write(t_filepath, t_filename); print(f"Added '{t_filename}' to zip."); files_added_count += 1
247
+
248
+ # Add Chapters (timed format from GPT)
249
+ # Check if chapters_timed contains the expected format (e.g., 'MM:SS - Title')
250
+ if chapters_timed and isinstance(chapters_timed, str) and not chapters_timed.startswith("Chyba:") and "ŽÁDNÉ KAPITOLY" not in chapters_timed and re.search(r"\d{1,2}:\d{2}\s*-", chapters_timed):
251
+ c_filename = "kapitoly_youtube.txt"; c_filepath = os.path.join(temp_dir, c_filename)
252
+ with open(c_filepath, 'w', encoding='utf-8') as f: f.write(chapters_timed) # Write the raw string (timed list)
253
+ zipf.write(c_filepath, c_filename); print(f"Added '{c_filename}' to zip."); files_added_count += 1
254
+ elif chapters_timed: print(f"Skipping chapters file (content invalid or not generated): {chapters_timed[:100]}...")
255
+
256
+ # Add Reels Suggestions (timed format from GPT)
257
+ # Check if reels_timed contains the expected format (e.g., 'Čas: ...')
258
+ if reels_timed and isinstance(reels_timed, str) and not reels_timed.startswith("Chyba:") and "ŽÁDNÉ NÁVRHY" not in reels_timed and "Čas:" in reels_timed:
259
+ r_filename = "navrhy_reels.txt"; r_filepath = os.path.join(temp_dir, r_filename)
260
+ with open(r_filepath, 'w', encoding='utf-8') as f: f.write(reels_timed) # Write the raw string (timed suggestions)
261
+ zipf.write(r_filepath, r_filename); print(f"Added '{r_filename}' to zip."); files_added_count += 1
262
+ elif reels_timed: print(f"Skipping reels file (content invalid or not generated): {reels_timed[:100]}...")
 
 
 
 
 
263
 
264
  # Add Article
265
  if article and isinstance(article, str) and not article.startswith("Chyba:"):
266
+ a_filename = "clanek_navrh.txt"; a_filepath = os.path.join(temp_dir, a_filename)
 
267
  with open(a_filepath, 'w', encoding='utf-8') as f: f.write(article)
268
+ zipf.write(a_filepath, a_filename); print(f"Added '{a_filename}' to zip."); files_added_count += 1
269
+
270
+ # Add SRT/VTT files (logic remains the same)
271
+ if srt_path and isinstance(srt_path, str) and os.path.exists(srt_path): srt_filename = f"{base_filename}.srt"; zipf.write(srt_path, srt_filename); files_added_count += 1; print(f"Added '{srt_filename}'")
272
+ if vtt_path and isinstance(vtt_path, str) and os.path.exists(vtt_path): vtt_filename = f"{base_filename}.vtt"; zipf.write(vtt_path, vtt_filename); files_added_count += 1; print(f"Added '{vtt_filename}'")
273
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
274
  if files_added_count == 0:
275
+ # ... (placeholder logic remains the same) ...
276
+ placeholder_filename = "info.txt"; placeholder_filepath = os.path.join(temp_dir, placeholder_filename)
277
+ with open(placeholder_filepath, 'w', encoding='utf-8') as f: f.write("Nebyly nalezeny žádné platné výstupy k zahrnutí.\n")
278
+ zipf.write(placeholder_filepath, placeholder_filename); print("Added info.txt to zip."); gr.Info("ZIP archiv neobsahuje žádné platné výstupy.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
279
 
 
 
 
 
 
 
280
 
281
+ final_zip_path_obj = tempfile.NamedTemporaryFile(delete=False, suffix='.zip', prefix=f"{base_filename}_"); final_zip_path = final_zip_path_obj.name; final_zip_path_obj.close()
282
+ shutil.copyfile(zip_filepath, final_zip_path); print(f"ZIP file created: {final_zip_path}"); gr.Info(f"ZIP soubor '{os.path.basename(final_zip_path)}' připraven.")
283
+ except Exception as e: zip_error = f"Chyba při vytváření ZIP archivu: {e}"; print(zip_error); traceback.print_exc(); gr.Error(zip_error); return None
284
  return final_zip_path
285
 
286
 
287
  # --- Main Processing Function ---
288
+ # <<< CHANGE: Restored timed chapters/reels generation logic >>>
289
+ def process_input(audio_filepath, segment_json_file, description, keywords, progress=gr.Progress(track_tqdm=True)):
290
+ """Processes either an audio file via Whisper or a JSON file with segments."""
291
+ # Outputs that will be displayed / used
292
+ formatted_transcript_w_chapters_output = "" # Main display with chapters inserted
293
+ chapters_output_display = "" # Textbox for timed chapters
294
+ reels_output_display = "" # Textbox for timed reels suggestions
295
+ # Internal states
296
  edited_transcript_for_state = ""
297
  context_for_state = ""
298
+ segments = [] # Populated from Whisper or JSON
299
+ chapters_parsed_list = [] # Parsed chapter data from GPT
300
  raw_transcript = None
301
+ audio_duration = 0.0 # Use float for duration
 
302
 
303
  try:
304
+ # --- INPUT SELECTION and SEGMENT PARSING ---
 
305
  input_source = "Neznámý"
306
+ if segment_json_file is not None:
307
+ # ... (JSON Parsing logic remains the same as previous version) ...
308
+ input_source = "JSON segmenty"
309
+ print(f"Processing JSON file: {segment_json_file.name}")
310
+ gr.Info(f"Zpracovávám segmenty z JSON: {os.path.basename(segment_json_file.name)}")
311
  try:
312
+ with open(segment_json_file.name, 'r', encoding='utf-8') as f: json_data = json.load(f)
313
+ if not isinstance(json_data, list): raise ValueError("JSON neobsahuje seznam.")
314
+ parsed_segments = []; temp_raw_transcript_parts = []; last_end_time = 0.0
315
+ for i, item in enumerate(json_data):
316
+ # ... (validation and parsing logic using parse_specific_timecode) ...
317
+ if not isinstance(item, dict) or "timestamp" not in item or "text" not in item: continue
318
+ try:
319
+ time_range = item["timestamp"]; text = str(item.get("text", "")).strip()
320
+ start_str, end_str = map(str.strip, time_range.split('-'))
321
+ start_seconds = parse_specific_timecode(start_str)
322
+ end_seconds = parse_specific_timecode(end_str)
323
+ if start_seconds < 0 or end_seconds < start_seconds: continue
324
+ parsed_segments.append({"start": start_seconds, "end": end_seconds, "text": text})
325
+ temp_raw_transcript_parts.append(text); last_end_time = max(last_end_time, end_seconds)
326
+ except Exception as e: print(f"Chyba parsování JSON segmentu {i}: {e}"); continue # Skip problematic segment
327
+ if not parsed_segments: raise ValueError("JSON neobsahuje platné segmenty.")
328
+ segments = parsed_segments; raw_transcript = " ".join(temp_raw_transcript_parts)
329
+ audio_duration = last_end_time if last_end_time > 0 else 1.0 # Avoid zero duration
330
+ detected_language = "N/A (Segmenty z JSON)"; audio_filepath = None
331
+ except Exception as e: raise ValueError(f"Chyba zpracování JSON: {e}")
332
 
333
  elif audio_filepath is not None:
334
+ # ... (Audio processing logic remains the same, populates segments and audio_duration) ...
335
+ input_source = "Audio soubor"; print(f"Processing audio: {audio_filepath}")
336
+ if not client: raise Exception("OpenAI klient není inicializován.")
337
+ progress(0.1, desc="Přepis..."); print(f"Transcribing: {audio_filepath}"); gr.Info("Spouštím přepis...")
338
+ try: file_size = os.path.getsize(audio_filepath); # Check size > 25MB
339
+ if file_size > 25 * 1024 * 1024: raise ValueError(f"Audio soubor ({file_size / 1024 / 1024:.1f} MB) je příliš velký (>25MB).")
340
+ except OSError as e: print(f"Warning: Size check failed - {e}")
341
+ 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"])
342
+ if not (transcription_response and hasattr(transcription_response, 'text')): raise Exception(f"Přepis Whisper selhal: {transcription_response}")
343
+ raw_transcript = transcription_response.text or ""; detected_language = getattr(transcription_response, 'language', 'N/A')
344
+ print(f"Transcription OK. Lang: {detected_language}")
345
+ whisper_segments_raw = getattr(transcription_response, 'segments', [])
346
+ segments = []; last_end_time = 0.0
347
+ for seg in whisper_segments_raw: # Validate and convert structure
348
+ seg_dict = {}; valid = False
349
+ if isinstance(seg, dict) and all(k in seg for k in ['start', 'end', 'text']): seg_dict = seg; valid = True
350
+ elif hasattr(seg, 'start') and hasattr(seg, 'end') and hasattr(seg, 'text'): seg_dict = {'start': seg.start, 'end': seg.end, 'text': getattr(seg, 'text', '')}; valid = True
351
+ if valid:
352
+ try:
353
+ start_f = float(seg_dict['start']); end_f = float(seg_dict['end']); text_s = str(seg_dict.get('text',''))
354
+ if start_f >= 0 and end_f >= start_f: segments.append({'start': start_f, 'end': end_f, 'text': text_s}); last_end_time = max(last_end_time, end_f)
355
+ else: print(f"Skipping Whisper segment invalid times: {seg_dict}")
356
+ except (TypeError, ValueError): print(f"Skipping Whisper segment non-numeric times: {seg_dict}")
357
+ else: print(f"Skipping invalid Whisper segment structure: {seg}")
358
+ audio_duration = last_end_time if last_end_time > 0 else 1.0 # Avoid zero duration
359
+ if not segments: print("Warning: No valid segments after Whisper processing.")
360
+ progress(0.2, desc="Přepis dokončen."); gr.Info(f"Přepis audia dokončen (jazyk: {detected_language}).")
361
+
362
+ else: gr.Warning("Nebyl poskytnut žádný vstup."); return "", "", "", "", [], "", "", [] # Return empty
363
+
364
+ # --- VALIDATE RAW TRANSCRIPT & DURATION ---
365
+ if raw_transcript is None or not raw_transcript.strip(): raise ValueError(f"Přepis (zdroj: {input_source}) je prázdný.")
366
+ if audio_duration <= 0: print("Warning: Audio duration is zero or negative. Chapter/Reel timing might be inaccurate."); audio_duration = 1.0 # Set a minimum duration
367
+ print(f"Přepis připraven (Zdroj: {input_source}, Délka textu: {len(raw_transcript)}, Délka audia: {audio_duration:.2f}s).")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
368
 
369
  # --- CONTEXT PREPARATION ---
370
  context_parts = [];
371
  if description and description.strip(): context_parts.append(f"Popis: {description.strip()}")
372
  if keywords and keywords.strip(): context_parts.append(f"Klíčová slova: {keywords.strip()}")
373
+ context_for_state = "\n".join(context_parts) if context_parts else "Žádný kontext."; print(f"Context: {context_for_state}")
374
+
375
+ # --- EDITING ---
376
+ progress(0.3, desc=f"Úprava textu ({GPT_MODEL})..."); print("Editing transcript..."); gr.Info("Spouštím úpravu textu GPT...")
377
+ edit_prompt = f"""Jsi profesionální editor... (celý edit prompt) ...
378
+ VSTUPNÍ PŘEPIS (zdroj: '{input_source}'):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
379
  ---
380
  {raw_transcript}
381
  ---
382
+ POŽADOVANÝ VÝSTUP (čistý text v ČEŠTINĚ):"""
383
+ edit_system_message="Jsi AI editor..."
384
  edited_transcript_for_state = call_gpt(edit_prompt, system_message=edit_system_message)
385
+ if edited_transcript_for_state.startswith("Chyba:") or not edited_transcript_for_state or not edited_transcript_for_state.strip(): raise Exception(f"Chyba editace GPT: {edited_transcript_for_state}")
386
+ print("Editing OK."); gr.Info("Úprava textu dokončena.")
387
 
388
+ # --- CHAPTERS (Generate titles AND times based on duration) ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
389
  progress(0.5, desc=f"Generování kapitol ({GPT_MODEL})...")
390
+ chapters_output_display = "Kapitoly nebyly vygenerovány." # Display variable
391
+ chapters_for_zip = "" # State variable for zip
392
+ print("Generating chapter titles and times..."); gr.Info("Generuji návrhy kapitol (vč. časů)...")
393
+ text_length_chars = len(edited_transcript_for_state); # Estimate based on text length
394
+ if text_length_chars < 2000: num_chapters = 3
395
+ elif text_length_chars < 10000: num_chapters = 5
396
+ else: num_chapters = 7 + int(math.log10(text_length_chars/10000)) * 2 # Scale slightly with length
397
+ num_chapters = min(max(num_chapters, 1), 15) # Clamp between 1 and 15
398
+ print(f"Requesting ~{num_chapters} chapters for duration {audio_duration:.0f}s...")
 
 
 
 
399
  try:
400
+ # <<< CHANGE: Updated Chapter Prompt - REQUESTS TIMES within duration >>>
401
+ chapter_prompt = f"""Analyzuj následující text v ČEŠTINĚ. Celková délka původního záznamu je přibližně {int(audio_duration)} sekund. Vygeneruj přibližně {num_chapters} relevantních kapitol.
402
 
403
+ Kontext (nepovinné): {context_for_state}
404
+ Celková délka záznamu: {format_timestamp(audio_duration, precision='seconds')}
405
 
406
  VSTUPNÍ TEXT K ANALÝZE (ČEŠTINA):
407
  ---
 
409
  ---
410
 
411
  Instrukce pro generování kapitol:
412
+ 1. Identifikuj hlavní témata v textu.
413
+ 2. Pro každé téma urči **reálný čas začátku** ve formátu HH:MM:SS (nebo MM:SS). Čas umísti **logicky v rámci celkové délky záznamu ({format_timestamp(audio_duration, precision='seconds')})** podle toho, kde se téma v textu nachází. První kapitola MUSÍ začínat 00:00:00 (nebo 00:00). Časy musí být vzestupné a nesmí překročit celkovou délku.
414
+ 3. Vytvoř krátký, výstižný název tématu v ČEŠTINĚ (max 5-7 slov).
415
  4. Naformátuj každou kapitolu PŘESNĚ jako: HH:MM:SS - Název tématu (nebo MM:SS - Název tématu). Každá kapitola na novém řádku.
416
+ 5. Seřaď kapitoly chronologicky.
417
 
418
+ POŽADOVANÝ VÝSTUP: Vrať POUZE seznam kapitol ve formátu 'ČAS - Název'. Pokud nenajdeš smysluplné kapitoly, vrať POUZE text 'ŽÁDNÉ KAPITOLY'."""
419
+ chapter_system_message="Jsi AI asistent, který generuje POUZE seznam YouTube kapitol ve formátu 'HH:MM:SS - Název'/'MM:SS - Název' nebo text 'ŽÁDNÉ KAPITOLY'."
420
  chapters_raw = call_gpt(chapter_prompt, system_message=chapter_system_message)
421
  print(f"Raw Chapters Output from GPT:\n---\n{chapters_raw}\n---")
422
  if not chapters_raw.startswith("Chyba:") and "ŽÁDNÉ KAPITOLY" not in chapters_raw and chapters_raw.strip():
423
+ chapters_parsed_list = parse_chapters(chapters_raw) # Use the restored parser
424
+ if chapters_parsed_list:
425
+ # Adjust first chapter to 0 if needed, ensure times are within duration
426
+ if chapters_parsed_list[0]['time'] != 0: chapters_parsed_list[0]['time'] = 0
427
+ chapters_parsed_list = [ch for ch in chapters_parsed_list if ch['time'] <= audio_duration] # Filter out chapters beyond duration
428
+ if chapters_parsed_list:
429
+ chapters_output_display = "\n".join([f"{format_yt_timestamp(ch['time'])} - {ch['title']}" for ch in chapters_parsed_list])
430
+ chapters_for_zip = chapters_output_display # Store for zip
431
+ print("Chapters OK."); gr.Info("Návrhy kapitol vygenerovány.")
432
+ else: chapters_output_display = "Kapitoly vygenerovány, ale žádná nebyla v rámci délky záznamu."; gr.Warning(chapters_output_display)
433
+ else: chapters_output_display = "Nepodařilo se rozpoznat formát kapitol."; print("Chapter parsing failed."); gr.Warning(chapters_output_display)
434
+ elif "ŽÁDNÉ KAPITOLY" in chapters_raw: chapters_output_display = "Žádné smysluplné kapitoly nenalezeny."; print(chapters_output_display); gr.Info(chapters_output_display)
435
+ else: chapters_output_display = chapters_raw if chapters_raw.startswith("Chyba:") else "Generování kapitol selhalo."; print(chapters_output_display); gr.Warning(chapters_output_display)
436
+ # Store the raw output (or error) for the zip state if parsing failed but output exists
437
+ if not chapters_for_zip and chapters_raw and not chapters_raw.startswith("Chyba:"): chapters_for_zip = chapters_raw
438
+
439
+ except Exception as e: chapters_output_display = f"Chyba při generování kapitol: {e}"; print(chapters_output_display); traceback.print_exc(); gr.Error(chapters_output_display)
440
+ if not chapters_for_zip: chapters_for_zip = chapters_output_display # Ensure zip state reflects display
441
+
442
+
443
+ # --- REELS (Generate description, quote, AND times based on duration) ---
 
 
 
 
 
 
 
444
  progress(0.7, desc=f"Generování Reels ({GPT_MODEL})...")
445
+ reels_output_display = "Návrhy pro Reels nebyly vygenerovány." # Display variable
446
+ reels_for_zip = "" # State variable for zip
447
  if edited_transcript_for_state and not edited_transcript_for_state.startswith("Chyba:"):
448
+ print("Generating Reels suggestions with times..."); gr.Info("Generuji návrhy na Reels (vč. časů)...")
 
449
  try:
450
+ # <<< CHANGE: Updated Reels Prompt - REQUESTS TIMES within duration >>>
451
+ reels_prompt = f"""Analyzuj následující text v ČEŠTINĚ. Celková délka původního záznamu je {audio_duration:.1f} sekund. Identifikuj 3-5 krátkých (cca 15-45 sekund), zajímavých úseků pro Reels/TikTok.
452
 
453
+ Kontext (nepovinné): {context_for_state}
454
+ Celková délka záznamu: {format_timestamp(audio_duration, precision='seconds')}
455
 
456
  VSTUPNÍ TEXT K ANALÝZE (ČEŠTINA):
457
  ---
 
459
  ---
460
 
461
  Instrukce pro každý návrh:
462
+ 1. Urči **reálný čas začátku a konce** úseku ve formátu HH:MM:SS.ms (nebo MM:SS.ms). Časy umísti **logicky v rámci celkové délky záznamu ({format_timestamp(audio_duration, precision='seconds')})** podle pozice úseku v textu. Začátek a konec musí být v rámci délky záznamu a konec musí být po začátku. Délka úseku by měla být mezi 15-45 sekundami.
463
+ 2. Napiš stručný, lákavý POPIS obsahu úseku (1-2 věty).
464
+ 3. Vyber krátkou, údernou CITACI/frázi přímo z daného úseku textu (v uvozovkách).
465
 
466
+ POŽADOVANÝ VÝSTUP: Vrať POUZE seznam návrhů ve formátu níže, oddělených prázdným řádkem. Pokud nenajdeš vhodné úseky, vrať POUZE text "ŽÁDNÉ NÁVRHY".
467
 
468
  Formát pro každý návrh:
469
  Čas: HH:MM:SS.ms - HH:MM:SS.ms
470
  Popis: [Stručný popis]
471
  Citace: „[Přesná citace z textu]“"""
472
+ reels_system_message="Jsi AI asistent, který generuje POUZE seznam návrhů pro Reels ve formátu 'Čas: ...\nPopis: ...\nCitace: ...' nebo text 'ŽÁDNÉ NÁVRHY'."
473
  reels_result = call_gpt(reels_prompt, system_message=reels_system_message)
474
  print(f"Raw Reels Output from GPT:\n---\n{reels_result}\n---")
 
475
  if not reels_result.startswith("Chyba:") and "ŽÁDNÉ NÁVRHY" not in reels_result and "Čas:" in reels_result and "Popis:" in reels_result and "Citace:" in reels_result :
476
+ # Basic validation if times look roughly correct (optional)
477
+ # TODO: Could add regex validation for time format here
478
+ reels_output_display = reels_result.strip()
479
+ reels_for_zip = reels_output_display
480
+ print("Reels OK."); gr.Info("Návrhy na Reels vygenerovány.")
481
  elif "ŽÁDNÉ NÁVRHY" in reels_result:
482
+ reels_output_display = "Nebyly nalezeny žádné vhodné úseky pro Reels."
483
+ print(reels_output_display); gr.Info(reels_output_display)
 
484
  else:
485
+ reels_output_display = reels_result if reels_result.startswith("Chyba:") else "Generování Reels selhalo nebo vrátilo neočekávaný formát."
486
+ print(f"Reels output unexpected: {reels_output_display[:200]}..."); gr.Warning(reels_output_display)
487
+ # Store raw output for zip if needed
488
+ if not reels_for_zip and reels_result and not reels_result.startswith("Chyba:"): reels_for_zip = reels_result
 
 
 
 
 
 
489
 
490
+ except Exception as e: reels_output_display = f"Chyba při generování Reels: {e}"; print(reels_output_display); traceback.print_exc(); gr.Error(reels_output_display)
491
+ else: reels_output_display = "Nelze generovat Reels (chybí platný editovaný přepis)."
492
+ if not reels_for_zip: reels_for_zip = reels_output_display # Ensure zip state reflects display
493
 
494
+ # --- Final Output Prep ---
495
  progress(0.9, desc="Formátování výstupu...")
496
+ # <<< CHANGE: Use format_transcript_with_chapters if chapters were parsed >>>
497
+ if chapters_parsed_list and edited_transcript_for_state and not edited_transcript_for_state.startswith("Chyba:"):
498
  print("Formatting transcript with generated chapters...")
499
+ formatted_transcript_w_chapters_output = format_transcript_with_chapters(edited_transcript_for_state, chapters_parsed_list, audio_duration)
 
 
 
 
 
500
  print("Formatted transcript with chapters prepared.")
501
  elif edited_transcript_for_state and not edited_transcript_for_state.startswith("Chyba:"):
502
+ formatted_transcript_w_chapters_output = edited_transcript_for_state # Show plain edited if no chapters
503
+ print("Chapters not available, displaying plain edited transcript.")
 
504
  else:
505
+ formatted_transcript_w_chapters_output = edited_transcript_for_state # Show error if editing failed
506
+
507
+ progress(1.0, desc="Hotovo!"); print(f"Processing OK (Source: {input_source})."); gr.Info("Zpracování dokončeno.")
508
+
509
+ # <<< CHANGE: Return structure updated for display and state >>>
510
+ # Display: formatted transcript, chapters with times, reels with times
511
+ # State: edited transcript, context, segments, chapters with times, reels with times
512
+ return formatted_transcript_w_chapters_output, chapters_output_display, reels_output_display, \
513
+ edited_transcript_for_state, context_for_state, segments, chapters_for_zip, reels_for_zip
514
+
515
+ except ValueError as ve: error_message = f"Chyba vstupu: {ve}"; print(error_message); gr.Error(error_message); return "", "", "", "", [], "", "", []
516
+ except Exception as e: error_message = f"Neočekávaná chyba: {e}"; print(error_message); traceback.print_exc(); gr.Error(error_message); return error_message, "", "", "", [], "", "", []
 
 
 
 
 
 
 
 
 
 
 
 
517
 
518
 
519
  # --- Gradio Interface Definition ---
520
  theme = gr.themes.Default(primary_hue=gr.themes.colors.blue, secondary_hue=gr.themes.colors.sky)
521
 
522
+ with gr.Blocks(theme=theme, title="WhisperBitch v2.2 (Timed Chapters)") as demo:
523
+ # <<< CHANGE: Updated Title and Info Text >>>
524
+ gr.Markdown("# 🧠 WhisperBitch v2.2 (Časované Kapitoly/Reels)", elem_id="app-title")
525
+ gr.Markdown("Zpracování audia (Whisper) nebo JSON segmentů. Generuje časované kapitoly a Reels.", elem_id="app-subtitle")
526
+ gr.Markdown("Audio limit ~25MB. JSON: `[{\"timestamp\": \"HH:MM:SS,ms-...\", \"text\": \"...\"}, ...]`. Kapitoly/Reels používají časy generované GPT na základě celkové délky.", elem_id="time-info")
527
+
528
+ # State variables (remain the same, but content interpretation changes slightly)
529
+ transcript_state = gr.State(value="") # Stores CLEAN edited transcript
530
+ context_state = gr.State(value="")
531
+ segments_state = gr.State(value=[]) # Stores segments (with PRECISE times from Whisper/JSON)
532
+ chapters_state = gr.State(value="") # Stores chapter list WITH times (GPT generated)
533
+ reels_state = gr.State(value="") # Stores reels suggestions WITH times (GPT generated)
534
+ article_state = gr.State(value="")
535
+ srt_path_state = gr.State(value=None)
536
+ vtt_path_state = gr.State(value=None)
 
537
 
538
  # --- UI Layout ---
539
  with gr.Row():
540
  # --- Input Column ---
541
  with gr.Column(scale=1, min_width=350):
542
+ gr.Markdown("### 1. Vstup")
543
  with gr.Tabs():
544
  with gr.TabItem("🎤 Audio"):
545
+ audio_input = gr.Audio(type="filepath", label="Nahrát audio (max ~25MB)", sources=["upload", "microphone"])
546
+ with gr.TabItem("📊 Segmenty (JSON)"):
547
+ segment_json_input = gr.File(label="Nahrát JSON segmenty (.json)", file_types=[".json"])
548
+ gr.Markdown("<small>Formát: `[{\"timestamp\": \"HH:MM:SS,ms-...\", ...}]`</small>")
 
 
 
 
 
 
 
 
 
 
549
  gr.Markdown("### 2. Kontext (nepovinné)")
550
+ description_input = gr.Textbox(label="Popis / Téma", lines=3)
551
+ keywords_input = gr.Textbox(label="Klíčová slova", lines=3)
 
552
  submit_button = gr.Button("🚀 Zpracovat Vstup", variant="primary", elem_id="submit-button")
553
 
554
  # --- Output Column ---
555
  with gr.Column(scale=2, min_width=600):
556
+ gr.Markdown("### 3. Výstupy")
557
+ # <<< CHANGE: Main output now includes chapters again >>>
558
  edited_output_formatted = gr.Textbox(label="✅ Upravený přepis s kapitolami (CZ)", lines=15, interactive=False, show_copy_button=True)
559
  with gr.Row():
560
+ # <<< CHANGE: Labels updated >>>
561
  chapters_output = gr.Textbox(label="🎬 Kapitoly pro YouTube (CZ)", lines=7, interactive=False, show_copy_button=True, scale=1)
562
  reels_output = gr.Textbox(label="🎬 Reels / TikTok návrhy (CZ)", lines=7, interactive=False, show_copy_button=True, scale=1)
563
 
564
+ # --- Optional Accordions --- (Article remains the same)
565
+ with gr.Accordion("📰 Generování článku (volitelné)", open=False):
566
+ # ... (article UI remains the same) ...
567
+ article_extra_prompt_input = gr.Textbox(label="⭐ Extra pokyny pro článek", lines=2)
568
  generate_article_button = gr.Button("✍️ Vygenerovat článek", variant="secondary")
569
  article_output_display = gr.Textbox(label="Článek (návrh v CZ)", lines=20, interactive=False, show_copy_button=True)
570
 
571
+ with gr.Accordion("📺 Generování titulků (volitelné)", open=False):
572
+ gr.Markdown("Generuje titulky s **původními přesnými časy** (z audia/JSONu) a **nově editovaným textem**.", elem_id="subs-info")
573
+ # ... (SRT/VTT buttons remain the same) ...
574
  with gr.Row():
575
  generate_srt_button = gr.Button("Generovat .SRT", variant="secondary")
576
  generate_vtt_button = gr.Button("Generovat .VTT", variant="secondary")
577
  with gr.Row():
578
+ srt_output_ondemand = gr.File(label="SRT Titulky ke stažení", interactive=False)
579
+ vtt_output_ondemand = gr.File(label="VTT Titulky ke stažení", interactive=False)
580
 
581
  # --- Download Button ---
582
  gr.Markdown("### 4. Stažení")
583
  download_button = gr.Button("⬇️ Stáhnout vše (.zip)", variant="primary")
584
+ download_file_output = gr.File(label="ZIP Archiv ke stažení", interactive=False)
585
 
586
  # --- Event Handling ---
587
+ # <<< CHANGE: Updated outputs for process_input >>>
 
588
  submit_button.click(
589
+ fn=process_input,
590
+ inputs=[ audio_input, segment_json_input, description_input, keywords_input ],
 
 
 
 
 
 
591
  outputs=[
592
+ edited_output_formatted, # Textbox: Formatted transcript with chapters
593
+ chapters_output, # Textbox: Timed Chapters list for display
594
+ reels_output, # Textbox: Timed Reels list for display
595
+ transcript_state, # State: Stores CLEAN edited transcript
596
+ context_state, # State: Stores context
597
+ segments_state, # State: Stores PRECISE segments (Whisper/JSON)
598
+ chapters_state, # State: Stores timed chapter list for ZIP
599
+ reels_state # State: Stores timed reels list for ZIP
600
  ],
 
601
  show_progress="full"
602
  )
603
 
604
+ # Other handlers remain the same
605
+ generate_article_button.click(fn=generate_article_content, inputs=[transcript_state, context_state, article_extra_prompt_input], outputs=[article_output_display, article_state], show_progress="full")
606
+ generate_srt_button.click(fn=generate_srt_file, inputs=[segments_state], outputs=[srt_output_ondemand, srt_path_state], show_progress="minimal")
607
+ generate_vtt_button.click(fn=generate_vtt_file, inputs=[segments_state], outputs=[vtt_output_ondemand, vtt_path_state], show_progress="minimal")
608
+ # <<< CHANGE: Pass formatted transcript to ZIP function >>>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
609
  download_button.click(
610
  fn=create_download_zip,
611
  inputs=[
612
+ edited_output_formatted, # Pass the transcript with chapters inserted
613
  chapters_state,
614
  reels_state,
615
+ srt_path_state,
616
+ vtt_path_state,
617
  article_state
618
  ],
619
+ outputs=[download_file_output],
620
  show_progress="minimal"
621
  )
622
 
623
  # --- Launch ---
624
  if __name__ == "__main__":
625
+ if not client: print("\n!!! KRITICKÁ CHYBA: OpenAI klient není inicializován... !!!\n")
626
+ else: print("\nOpenAI client OK. Starting Gradio...")
 
 
 
 
 
 
 
 
 
 
 
627
  demo.launch(share=False)