# --- IMPORTS FIRST --- import gradio as gr import openai import os import datetime import tempfile import traceback import math import re # Keep re for parsing chapters and sanitizing filenames import zipfile import shutil import json # --- Configuration & OpenAI Client Setup --- OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") WHISPER_MODEL = "whisper-1" GPT_MODEL = "gpt-4.1" client = None if OPENAI_API_KEY: try: client = openai.OpenAI(api_key=OPENAI_API_KEY) print("OpenAI Client OK.") except Exception as e: print(f"Error initializing OpenAI Client: {e}") else: print("Warning: OPENAI_API_KEY environment variable not set. OpenAI features will fail.") # --- Helper Functions --- # format_timestamp, format_yt_timestamp remain the same def format_timestamp(seconds, format_type='srt', precision='milliseconds'): if not isinstance(seconds, (int, float)) or seconds < 0: seconds = 0 seconds_int = int(seconds); milliseconds_part = seconds - seconds_int; milliseconds = int(milliseconds_part * 1000) td = datetime.timedelta(seconds=seconds_int); total_seconds = int(td.total_seconds()) hours, remainder = divmod(total_seconds, 3600); minutes, seconds_rem = divmod(remainder, 60) if precision == 'seconds': return f"{hours:02}:{minutes:02}:{seconds_rem:02}" else: separator = ',' if format_type == 'srt' else '.'; return f"{hours:02}:{minutes:02}:{seconds_rem:02}{separator}{milliseconds:03}" def format_yt_timestamp(seconds): if not isinstance(seconds, (int, float)) or seconds < 0: seconds = 0 td = datetime.timedelta(seconds=int(seconds)); total_seconds = int(td.total_seconds()) hours, remainder = divmod(total_seconds, 3600); minutes, seconds_rem = divmod(remainder, 60) if hours > 0: return f"{hours}:{minutes:02}:{seconds_rem:02}" else: return f"{minutes:02}:{seconds_rem:02}" # <<< RESTORED: parse_chapters to handle GPT's timed output >>> def parse_chapters(chapter_text): """Parses chapter text (HH:MM:SS - Title) into a list of dictionaries.""" chapters = [] pattern = re.compile(r"^(?:(\d{1,2}):)?(\d{1,2}):(\d{2})\s*-\s*(.+)$", re.MULTILINE) if not chapter_text: return chapters print(f"Parsing chapter text from GPT:\n---\n{chapter_text}\n---") for match in pattern.finditer(chapter_text): try: hours_str = match.group(1); minutes_str = match.group(2); seconds_str = match.group(3); title = match.group(4).strip() 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 if not (0 <= minutes < 60 and 0 <= seconds < 60): print(f"Skipping invalid time in chapter: '{match.group(0)}'"); continue total_seconds = hours * 3600 + minutes * 60 + seconds chapters.append({"time": total_seconds, "title": title}) except Exception as e: print(f"Error parsing chapter line: '{match.group(0)}' - {e}") try: chapters.sort(key=lambda x: x['time']) except Exception as e: print(f"Error sorting chapters: {e}") print(f"Parsed chapters from GPT: {chapters}") return chapters # <<< RESTORED: format_transcript_with_chapters to insert timed chapters >>> def format_transcript_with_chapters(edited_transcript, parsed_chapters, audio_duration): """Formats transcript with chapter headings using known audio duration.""" if not parsed_chapters or not edited_transcript or audio_duration <= 0: return edited_transcript output_parts = []; last_char_pos = 0; total_len = len(edited_transcript) print(f"Formatting transcript with chapters using actual duration: {audio_duration:.0f}s") for i, chapter in enumerate(parsed_chapters): # Use the time from the parsed chapter generated by GPT chapter_time = chapter.get('time', 0) # Estimate position based on GPT's time relative to total duration approx_char_pos = int((chapter_time / audio_duration) * total_len) if audio_duration > 0 else 0 # Heuristic to find a nearby newline (same logic as before) 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)) insert_pos = edited_transcript.rfind('\n', search_window_start, approx_char_pos) if insert_pos == -1 or insert_pos < last_char_pos: insert_pos = edited_transcript.find('\n', approx_char_pos, approx_char_pos + 100) if insert_pos == -1: space_pos = edited_transcript.rfind(' ', search_window_start, approx_char_pos) insert_pos = space_pos + 1 if space_pos != -1 and space_pos > last_char_pos else approx_char_pos else: insert_pos += 1 else: insert_pos += 1 insert_pos = min(max(last_char_pos, insert_pos), total_len) output_parts.append(edited_transcript[last_char_pos:insert_pos]) heading_prefix = "\n\n" if insert_pos > 0 else "" # Use the time from the chapter dict, format it heading = f"{heading_prefix}({format_timestamp(chapter_time, precision='seconds')} - {chapter['title']})\n" output_parts.append(heading); last_char_pos = insert_pos output_parts.append(edited_transcript[last_char_pos:]) result = "".join(output_parts).strip() print("Transcript formatting with chapters complete.") return result # parse_specific_timecode remains the same def parse_specific_timecode(tc_str): tc_str = tc_str.strip(); match = re.match(r'(\d{2}):(\d{2}):(\d{2}),(\d{3})', tc_str) if match: h, m, s, ms = map(int, match.groups()) if not (0 <= m < 60 and 0 <= s < 60 and 0 <= ms < 1000): raise ValueError(f"Invalid time values: {tc_str}") return float(h * 3600 + m * 60 + s + ms / 1000.0) else: match = re.match(r'(\d{2}):(\d{2}),(\d{3})', tc_str) # Try MM:SS,ms if match: m, s, ms = map(int, match.groups()) if not (0 <= m < 60 and 0 <= s < 60 and 0 <= ms < 1000): raise ValueError(f"Invalid time values: {tc_str}") return float(m * 60 + s + ms / 1000.0) else: raise ValueError(f"Unknown timecode format: {tc_str}. Expected HH:MM:SS,ms or MM:SS,ms") # format_srt, format_vtt remain the same def format_srt(segments): srt_content = "" # ... (implementation remains the same) ... if not segments or not isinstance(segments, list): return "" segment_count = 0 for i, segment_data in enumerate(segments): 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 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 "" except (ValueError, TypeError) as e: print(f"SRT segment {i} invalid time/text type: {e}"); continue if start_s < 0 or end_s < start_s: print(f"SRT segment {i} invalid times: {start_s}-{end_s}"); continue start_time = format_timestamp(start_s, 'srt'); end_time = format_timestamp(end_s, 'srt') max_length = 42; words = text.split(); lines = []; current_line = "" for word in words: if not current_line: current_line = word elif len(current_line) + len(word) + 1 <= max_length: current_line += " " + word else: lines.append(current_line); current_line = word if current_line: lines.append(current_line) formatted_text = "\n".join(l for l in lines if l) if formatted_text: segment_count += 1; srt_content += f"{segment_count}\n{start_time} --> {end_time}\n{formatted_text}\n\n" return srt_content def format_vtt(segments): vtt_content = "WEBVTT\n\n" # ... (implementation remains the same) ... if not segments or not isinstance(segments, list): return vtt_content for i, segment_data in enumerate(segments): 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 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 "" except (ValueError, TypeError) as e: print(f"VTT segment {i} invalid time/text type: {e}"); continue if start_s < 0 or end_s < start_s: print(f"VTT segment {i} invalid times: {start_s}-{end_s}"); continue start_time = format_timestamp(start_s, 'vtt'); end_time = format_timestamp(end_s, 'vtt') max_length = 42; words = text.split(); lines = []; current_line = "" for word in words: if not current_line: current_line = word elif len(current_line) + len(word) + 1 <= max_length: current_line += " " + word else: lines.append(current_line); current_line = word if current_line: lines.append(current_line) formatted_text = "\n".join(l for l in lines if l) if formatted_text: vtt_content += f"{start_time} --> {end_time}\n{formatted_text}\n\n" return vtt_content # call_gpt remains the same def call_gpt(prompt, system_message="Jsi užitečný AI asistent."): # ... (implementation remains the same) ... if not client: print("Error: OpenAI client not initialized."); return "Chyba: OpenAI klient není inicializován." try: 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} ]) result = response.choices[0].message.content.strip(); print("GPT Call OK.") if not result or len(result) < 5: print(f"Warning: GPT returned potentially empty/short response: '{result}'") # Adjusted length check slightly return result except openai.NotFoundError as e: print(f"GPT Error: Model '{GPT_MODEL}' not found..."); return f"Chyba GPT: Model '{GPT_MODEL}' nenalezen..." except openai.RateLimitError as e: print(f"GPT Error: Rate limit exceeded."); return f"Chyba GPT: Překročen limit požadavků..." except openai.APIConnectionError as e: print(f"GPT Error: Network issue."); return f"Chyba GPT: Problém s připojením..." except Exception as e: print(f"An unexpected GPT Error occurred: {e}"); traceback.print_exc(); return f"Chyba GPT: Neočekávaná chyba - {e}" # --- START KÓDU PRO generate_article_content --- def generate_article_content(transcript_state, context_state, article_extra_prompt, progress=gr.Progress(track_tqdm=True)): """Generates structured article content including SEO fields using GPT based on the transcript.""" article_result = "Chyba: Generování článku selhalo." try: print("--- generate_article_content called ---") # Input validation if not transcript_state or transcript_state.startswith("Chyba:"): gr.Warning("Nelze generovat článek bez platného přepisu.") return "Chyba: Nelze generovat článek bez platného přepisu.", "Chyba: Nelze generovat článek bez platného přepisu." if not client: return "Chyba: OpenAI klient není inicializován.", "Chyba: OpenAI klient není inicializován." progress(0.1, desc="Příprava na generování článku..."); print("Generating article...") word_count = len(str(transcript_state).split()) is_long_article = word_count > 400 # <<< Updated ARTICLE PROMPT v4.1 (More directive SEO Title KW) >>> article_prompt = f"""POKYN: Jsi AI redaktor a SEO specialista. Vygeneruj komplexní výstup POUZE ve formátu **čistého textu (žádný Markdown ani HTML!)** v ČEŠTINĚ na základě VSTUPŮ níže. Striktně dodrž požadovaný formát, strukturu a všechny instrukce. == VSTUP: Kontext == {context_state if context_state else "Není k dispozici."} == VSTUP: Editovaný přepis == --- START --- {transcript_state} --- END --- == VSTUP: Extra pokyny od uživatele == {article_extra_prompt if article_extra_prompt else "Žádné specifické pokyny."} == POŽADOVANÝ VÝSTUP (Striktně dodrž formát! Pouze čistý text!) == Sociální sítě: (Vytvoř 3 stručné, poutavé verze s relevantními emoji 📱👍🤔 a 2-3 relevantními #hashtagy pro každou) Verze A (Krátká, úderná): [Text krátké verze] Verze B (Informativní, shrnutí): [Text informativní verze] Verze C (Otázka nebo zajímavost): [Text originální/otázka verze] Návrhy titulků: (Vytvoř PŘESNĚ 5 variant, každou na novém řádku, formát 'Typ:\\nNázev') Popisný: [Název popisného titulku vystihující hlavní téma] Výrazný: [Název výrazného, možná kontroverzního nebo zvědavost budícího titulku] Citace: [**Doslovná, krátká, silná citace** z textu jako titulek v „českých uvozovkách“] Emotivní: [Název titulku apelující na emoce nebo osobní zkušenost] Otázka: [Zajímavá otázka týkající se obsahu jako titulek] SEO Meta Title: # <<< ZMĚNA ZDE v instrukci: >>> (Vytvoř SEO titulek: **Musí začínat hlavním tématem/klíčovým slovem (ideálně podst. jm. v 1. pádu)**. Celkem max 65 znaků. Obsahuje číslici, pokud se přirozeně hodí. Je podobný hlavnímu titulku.) [Text Meta Title] SEO Meta Description: (Vytvoř SEO popis: **max 120 znaků**, výstižné shrnutí článku, lákavé ke kliknutí, může obsahovat klíčové slovo.) [Text Meta Description] Článek: Perex (Napiš výstižný perex o rozsahu cca 4-6 vět, který shrne nejdůležitější body a naláká ke čtení.) [Text perexu...] Co se dozvíte ({"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."}) - [Bod 1] - [Bod 2] ... [Mezititulek 1 - Výstižný název v češtině, bez formátování. Zkus opakovat klíčová slova.] (Napiš první část článku. Použij relevantní české mezititulky psané jako běžný text. **POUŽÍVEJ VÝHRADNĚ DOSLOVNÉ CITACE** z poskytnutého `VSTUP: Editovaný přepis`. Označuj je „českými uvozovkami“. **Nic v citacích neměň ani si nevymýšlej vlastní citace!** Pokud vhodná doslovná citace chybí, raději ji nepoužij. Text musí být čtivý a logicky strukturovaný.) [Text oddílu 1...] [Mezititulek 2 - Výstižný název v češtině, bez formátování. Zkus opakovat klíčová slova.] (Pokračuj v článku dalším oddílem s mezititulkem a **výhradně doslovnými citacemi**.) [Text oddílu 2...] (... pokračuj s dalšími mezititulky (opakuj klíčová slova) a **výhradně doslovnými citacemi** podle potřeby ...) [Závěrečný mezititulek nebo Shrnutí - Běžný text] (Krátké shrnutí nebo závěrečná myšlenka.) [Text závěrečného oddílu...] == KONEC SPECIFIKACE VÝSTUPU == 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. **NEPOUŽÍVEJ ŽÁDNÉ MARKDOWN ANI HTML ZNAČKY (ŽÁDNÉ ==, ####, **, ATD.)!** Vše piš jako čistý text. """ # <<< Updated SYSTEM MESSAGE v4 >>> 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. Striktně se vyhýbáš jakémukoli Markdown nebo HTML formátování. **Pro citace používáš výhradně doslovné úryvky z poskytnutého přepisu, pokud jsou požadovány.** Negeneruješ žádný jiný text, otázky ani komentáře. Soustředíš se na kvalitu, relevanci obsahu a dodržení formátu v čistém textu." progress(0.5, desc=f"Volání GPT ({GPT_MODEL})..."); gr.Info("Generuji návrh článku (vč. SEO) pomocí GPT...") # Info message article_result = call_gpt(article_prompt, system_message=system_msg) # Check for errors or suspiciously short results if article_result.startswith("Chyba GPT:") or not article_result or len(article_result) < 250: # Increased length check due to new fields if not article_result.startswith("Chyba GPT:") and article_result: error_detail = f"Generování článku vrátilo neočekávaný/krátký výsledek (Začátek: '{article_result[:100]}...'). Zkontrolujte prompt." else: error_detail = f"Generování článku selhalo/vrátilo prázdný výsledek: {article_result}" raise Exception(error_detail) # Optional check for Markdown if re.search(r'(^#+\s+)|(^==+\s*)|(\s*==+$)|([*_`])', article_result, re.MULTILINE): # Added check for *, _, ` print("Warning: Generated article might contain Markdown despite instructions!") gr.Warning("GPT v článku možná použilo Markdown i přes instrukce. Zkontrolujte výstup.") progress(1.0, desc="Článek vygenerován."); print("Article generation OK.") gr.Info("Návrh článku úspěšně vygenerován.") except Exception as e: error_message = f"Chyba při generování článku: {e}" print(error_message); traceback.print_exc(); gr.Error(error_message) article_result = error_message print(f"--- generate_article_content finished, returning result starting with: {str(article_result)[:150]}...") # Return the result for both the display component and the state variable return article_result, article_result # --- Konec kódu pro funkci generate_article_content --- # generate_srt_file / generate_vtt_file remain the same def generate_srt_file(segments_state): # ... (implementation remains the same) ... 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 print("Generating SRT file..."); srt_content = format_srt(segments_state) if not srt_content: gr.Warning("Nepodařilo se vygenerovat obsah SRT."); return None, None try: with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.srt', encoding='utf-8', prefix='sub_') as f: f.write(srt_content); srt_filepath = f.name print(f"SRT file generated: {srt_filepath}"); return srt_filepath, srt_filepath 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 def generate_vtt_file(segments_state): # ... (implementation remains the same) ... 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 print("Generating VTT file..."); vtt_content = format_vtt(segments_state) if not vtt_content or vtt_content.strip() == "WEBVTT": gr.Warning("Nepodařilo se vygenerovat obsah VTT."); return None, None try: with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.vtt', encoding='utf-8', prefix='sub_') as f: f.write(vtt_content); vtt_filepath = f.name print(f"VTT file generated: {vtt_filepath}"); return vtt_filepath, vtt_filepath 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 # <<< CHANGE: create_download_zip restored chapter/reels timed format assumption >>> def create_download_zip(transcript_formatted, chapters_timed, reels_timed, srt_path, vtt_path, article): """Creates a ZIP file containing all generated outputs.""" print("Attempting to create ZIP file...") final_zip_path = None base_filename = "prepisovac_vystupy" if article and isinstance(article, str) and not article.startswith("Chyba:"): # ... (extract title logic remains the same) ... title_match = re.search(r"Popisný:\s*\n(.+)", article, re.IGNORECASE) if not title_match: title_match = re.search(r"Návrhy titulků:\s*\n(?:.+\:\s*\n)?(.+)", article, re.IGNORECASE) if title_match: 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] print(f"Using base filename from article title: '{base_filename}'") else: print("Could not extract title from article, using default filename.") try: with tempfile.TemporaryDirectory() as temp_dir: zip_filename = f"{base_filename}.zip"; zip_filepath = os.path.join(temp_dir, zip_filename) print(f"Creating zip archive at: {zip_filepath}") files_added_count = 0 with zipfile.ZipFile(zip_filepath, 'w', zipfile.ZIP_DEFLATED) as zipf: # Add Formatted Transcript (with chapters inserted if available) if transcript_formatted and isinstance(transcript_formatted, str) and not transcript_formatted.startswith("Chyba:"): t_filename = "prepis_s_kapitolami.txt"; t_filepath = os.path.join(temp_dir, t_filename) with open(t_filepath, 'w', encoding='utf-8') as f: f.write(transcript_formatted) zipf.write(t_filepath, t_filename); print(f"Added '{t_filename}' to zip."); files_added_count += 1 # Add Chapters (timed format from GPT) # Check if chapters_timed contains the expected format (e.g., 'MM:SS - Title') 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): c_filename = "kapitoly_youtube.txt"; c_filepath = os.path.join(temp_dir, c_filename) with open(c_filepath, 'w', encoding='utf-8') as f: f.write(chapters_timed) # Write the raw string (timed list) zipf.write(c_filepath, c_filename); print(f"Added '{c_filename}' to zip."); files_added_count += 1 elif chapters_timed: print(f"Skipping chapters file (content invalid or not generated): {chapters_timed[:100]}...") # Add Reels Suggestions (timed format from GPT) # Check if reels_timed contains the expected format (e.g., 'Čas: ...') 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: r_filename = "navrhy_reels.txt"; r_filepath = os.path.join(temp_dir, r_filename) with open(r_filepath, 'w', encoding='utf-8') as f: f.write(reels_timed) # Write the raw string (timed suggestions) zipf.write(r_filepath, r_filename); print(f"Added '{r_filename}' to zip."); files_added_count += 1 elif reels_timed: print(f"Skipping reels file (content invalid or not generated): {reels_timed[:100]}...") # Add Article if article and isinstance(article, str) and not article.startswith("Chyba:"): a_filename = "clanek_navrh.txt"; a_filepath = os.path.join(temp_dir, a_filename) with open(a_filepath, 'w', encoding='utf-8') as f: f.write(article) zipf.write(a_filepath, a_filename); print(f"Added '{a_filename}' to zip."); files_added_count += 1 # Add SRT/VTT files (logic remains the same) 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}'") 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}'") if files_added_count == 0: # ... (placeholder logic remains the same) ... placeholder_filename = "info.txt"; placeholder_filepath = os.path.join(temp_dir, placeholder_filename) with open(placeholder_filepath, 'w', encoding='utf-8') as f: f.write("Nebyly nalezeny žádné platné výstupy k zahrnutí.\n") zipf.write(placeholder_filepath, placeholder_filename); print("Added info.txt to zip."); gr.Info("ZIP archiv neobsahuje žádné platné výstupy.") 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() 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.") 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 return final_zip_path # --- Main Processing Function --- # <<< CHANGE: Restored timed chapters/reels generation logic >>> # --- START KÓDU PRO process_input --- def process_input(audio_filepath, segment_json_file, description, keywords, progress=gr.Progress(track_tqdm=True)): """Processes either an audio file via Whisper or a JSON file with segments.""" # Outputs that will be displayed / used formatted_transcript_w_chapters_output = "" # Main display with chapters inserted chapters_output_display = "" # Textbox for timed chapters reels_output_display = "" # Textbox for timed reels suggestions # Internal states edited_transcript_for_state = "" context_for_state = "" segments = [] # Populated from Whisper or JSON chapters_parsed_list = [] # Parsed chapter data from GPT chapters_for_zip = "" # State variable for zip (timed chapter list) reels_for_zip = "" # State variable for zip (timed reels list) raw_transcript = None audio_duration = 0.0 # Use float for duration try: # --- INPUT SELECTION and SEGMENT PARSING --- input_source = "Neznámý" # Priority: JSON file > Audio file if segment_json_file is not None: input_source = "JSON segmenty" print(f"Processing JSON file: {segment_json_file.name}") gr.Info(f"Zpracovávám segmenty z JSON: {os.path.basename(segment_json_file.name)}") try: with open(segment_json_file.name, 'r', encoding='utf-8') as f: json_data = json.load(f) if not isinstance(json_data, list): raise ValueError("JSON neobsahuje seznam.") parsed_segments = []; temp_raw_transcript_parts = []; last_end_time = 0.0 for i, item in enumerate(json_data): if not isinstance(item, dict) or "timestamp" not in item or "text" not in item: continue try: time_range = item["timestamp"]; text = str(item.get("text", "")).strip() start_str, end_str = map(str.strip, time_range.split('-')) start_seconds = parse_specific_timecode(start_str) end_seconds = parse_specific_timecode(end_str) if start_seconds < 0 or end_seconds < start_seconds: continue parsed_segments.append({"start": start_seconds, "end": end_seconds, "text": text}) temp_raw_transcript_parts.append(text); last_end_time = max(last_end_time, end_seconds) except Exception as e: print(f"Chyba parsování JSON segmentu {i}: {e}"); continue if not parsed_segments: raise ValueError("JSON neobsahuje platné segmenty.") segments = parsed_segments; raw_transcript = " ".join(temp_raw_transcript_parts) audio_duration = last_end_time if last_end_time > 0 else 1.0 detected_language = "N/A (Segmenty z JSON)"; audio_filepath = None except Exception as e: raise ValueError(f"Chyba zpracování JSON: {e}") elif audio_filepath is not None: input_source = "Audio soubor"; print(f"Processing audio: {audio_filepath}") if not client: raise Exception("OpenAI klient není inicializován.") progress(0.1, desc="Přepis..."); print(f"Transcribing: {audio_filepath}"); gr.Info("Spouštím přepis...") try: # Check file size file_size = os.path.getsize(audio_filepath) if file_size > 25 * 1024 * 1024: raise ValueError(f"Audio soubor ({file_size / 1024 / 1024:.1f} MB) je příliš velký (>25MB).") except OSError as e: print(f"Warning: Size check failed - {e}") 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"]) if not (transcription_response and hasattr(transcription_response, 'text')): raise Exception(f"Přepis Whisper selhal: {transcription_response}") raw_transcript = transcription_response.text or ""; detected_language = getattr(transcription_response, 'language', 'N/A') print(f"Transcription OK. Lang: {detected_language}") whisper_segments_raw = getattr(transcription_response, 'segments', []) segments = []; last_end_time = 0.0 for seg in whisper_segments_raw: # Validate and convert structure seg_dict = {}; valid = False if isinstance(seg, dict) and all(k in seg for k in ['start', 'end', 'text']): seg_dict = seg; valid = True 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 if valid: try: start_f = float(seg_dict['start']); end_f = float(seg_dict['end']); text_s = str(seg_dict.get('text','')) 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) else: print(f"Skipping Whisper segment invalid times: {seg_dict}") except (TypeError, ValueError): print(f"Skipping Whisper segment non-numeric times: {seg_dict}") else: print(f"Skipping invalid Whisper segment structure: {seg}") audio_duration = last_end_time if last_end_time > 0 else 1.0 if not segments: print("Warning: No valid segments after Whisper processing.") progress(0.2, desc="Přepis dokončen."); gr.Info(f"Přepis audia dokončen (jazyk: {detected_language}).") else: gr.Warning("Nebyl poskytnut žádný vstup."); return "", "", "", "", [], "", "", [] # --- VALIDATE RAW TRANSCRIPT & DURATION --- if raw_transcript is None or not raw_transcript.strip(): raise ValueError(f"Přepis (zdroj: {input_source}) je prázdný.") if audio_duration <= 0: print("Warning: Audio duration is zero. Using 1s fallback."); audio_duration = 1.0 print(f"Přepis připraven (Zdroj: {input_source}, Délka textu: {len(raw_transcript)}, Délka audia: {audio_duration:.2f}s).") # --- CONTEXT PREPARATION --- context_parts = []; if description and description.strip(): context_parts.append(f"Popis: {description.strip()}") if keywords and keywords.strip(): context_parts.append(f"Klíčová slova: {keywords.strip()}") context_for_state = "\n".join(context_parts) if context_parts else "Žádný kontext."; print(f"Context: {context_for_state}") # --- EDITING --- progress(0.3, desc=f"Úprava textu ({GPT_MODEL})..."); print("Editing transcript..."); gr.Info("Spouštím úpravu textu GPT...") edit_prompt = f"""Jsi profesionální editor českého jazyka... (celý edit prompt, ten zůstal OK) ... VSTUPNÍ PŘEPIS (zdroj: '{input_source}'): --- {raw_transcript} --- POŽADOVANÝ VÝSTUP (čistý text v ČEŠTINĚ):""" edit_system_message="Jsi AI editor specializovaný na převod surového přepisu do čistého, editovaného českého textu..." # Shortened for brevity, use the full one edited_transcript_for_state = call_gpt(edit_prompt, system_message=edit_system_message) 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}") print("Editing OK."); gr.Info("Úprava textu dokončena.") # --- CHAPTERS (Generate titles AND times based on duration) --- progress(0.5, desc=f"Generování kapitol ({GPT_MODEL})...") chapters_output_display = "Kapitoly nebyly vygenerovány." chapters_for_zip = "" print("Generating chapter titles and times..."); gr.Info("Generuji návrhy kapitol (vč. časů)...") text_length_chars = len(edited_transcript_for_state); if text_length_chars < 2000: num_chapters = 3 elif text_length_chars < 10000: num_chapters = 5 else: num_chapters = 7 + int(math.log10(text_length_chars/10000)) * 2 if text_length_chars > 10000 else 7 # Avoid log10(0) num_chapters = min(max(num_chapters, 1), 15) print(f"Requesting ~{num_chapters} chapters for duration {audio_duration:.0f}s...") try: # Chapter Prompt requests times based on duration 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. Kontext (nepovinné): {context_for_state} Celková délka záznamu: {format_timestamp(audio_duration, precision='seconds')} VSTUPNÍ TEXT K ANALÝZE (ČEŠTINA): --- {edited_transcript_for_state} --- Instrukce pro generování kapitol: 1. Identifikuj hlavní témata v textu. 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. 3. Vytvoř krátký, výstižný název tématu v ČEŠTINĚ (max 5-7 slov). 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. 5. Seřaď kapitoly chronologicky. POŽADOVANÝ VÝSTUP: Vrať POUZE seznam kapitol ve formátu 'ČAS - Název'. Pokud nenajdeš smysluplné kapitoly, vrať POUZE text 'ŽÁDNÉ KAPITOLY'.""" 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'." chapters_raw = call_gpt(chapter_prompt, system_message=chapter_system_message) print(f"Raw Chapters Output from GPT:\n---\n{chapters_raw}\n---") if not chapters_raw.startswith("Chyba:") and "ŽÁDNÉ KAPITOLY" not in chapters_raw and chapters_raw.strip(): chapters_parsed_list = parse_chapters(chapters_raw) # Use the restored parser if chapters_parsed_list: if chapters_parsed_list[0]['time'] != 0: chapters_parsed_list[0]['time'] = 0 chapters_parsed_list = [ch for ch in chapters_parsed_list if ch['time'] <= audio_duration] if chapters_parsed_list: chapters_output_display = "\n".join([f"{format_yt_timestamp(ch['time'])} - {ch['title']}" for ch in chapters_parsed_list]) chapters_for_zip = chapters_output_display print("Chapters OK."); gr.Info("Návrhy kapitol vygenerovány.") else: chapters_output_display = "Kapitoly vygenerovány, ale žádná nebyla v rámci délky záznamu."; gr.Warning(chapters_output_display) else: chapters_output_display = "Nepodařilo se rozpoznat formát kapitol."; print("Chapter parsing failed."); gr.Warning(chapters_output_display) elif "ŽÁDNÉ KAPITOLY" in chapters_raw: chapters_output_display = "Žádné smysluplné kapitoly nenalezeny."; print(chapters_output_display); gr.Info(chapters_output_display) 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) if not chapters_for_zip and chapters_raw and not chapters_raw.startswith("Chyba:"): chapters_for_zip = chapters_raw # Store raw if parsing failed 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) if not chapters_for_zip: chapters_for_zip = chapters_output_display # <<< Updated REELS Generation Block >>> # --- REELS (Generate description, quote, AND times based on duration - ENHANCED PROMPT v2) --- progress(0.7, desc=f"Generování Reels ({GPT_MODEL})...") reels_output_display = "Návrhy pro Reels nebyly vygenerovány." # Display variable reels_for_zip = "" # State variable for zip if edited_transcript_for_state and not edited_transcript_for_state.startswith("Chyba:"): print("Generating Reels suggestions with enhanced criteria..."); gr.Info("Hledám nejlepší momenty pro Reels/TikTok...") try: # <<< Enhanced Reels Prompt v2 >>> 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 úseků (každý cca 15-45 sekund) s **nejvyšším potenciálem zaujmout** na sociálních sítích jako Reels/TikTok. Kontext (nepovinné): {context_for_state} Celková délka záznamu: {format_timestamp(audio_duration, precision='seconds')} VSTUPNÍ TEXT K ANALÝZE (ČEŠTINA): --- {edited_transcript_for_state} --- Instrukce pro výběr úseků: * Hledej momenty, které jsou **samostatně pochopitelné** a mají potenciál **zastavit uživatele při scrollování**. * Zaměř se na úseky obsahující jedno nebo více z následujících: * **Humor:** Vtipné poznámky, ironie, zábavné situace. * **Silné emoce:** Jasně vyjádřená radost, frustrace, překvapení atd. * **Kontroverze / Silný názor:** Výrazný, možná diskutabilní postoj. * **Překvapivý fakt / 'Aha!' moment:** Nečekaná nebo osvětlující informace. * **Zásadní sdělení / Klíčová myšlenka:** Jádro problému nebo důležitý závěr. * **Praktický tip / Rada:** Konkrétní, užitečná informace. Instrukce pro formát výstupu (pro každý nalezený úsek): 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. Délka úseku by měla být cca 15-45 sekund. Začátek a konec musí být v rámci délky záznamu a konec po začátku. 2. Napiš stručný, lákavý POPIS obsahu úseku (1-2 věty). 3. Vyber **jednu klíčovou, údernou a VÝHRADNĚ DOSLOVNOU CITACI** přímo z tohoto úseku textu (v „českých uvozovkách“). 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 splňující kritéria, vrať POUZE text "ŽÁDNÉ NÁVRHY". Nepoužívej Markdown. Formát pro každý návrh: Čas: HH:MM:SS.ms - HH:MM:SS.ms Popis: [Stručný popis] Citace: „[Doslovná citace z textu]“""" reels_system_message="Jsi expert na sociální média. Tvojí úlohou je identifikovat nejzajímavější úseky z textu pro Reels/TikTok podle zadaných kritérií a naformátovat je PŘESNĚ podle požadavků (Čas/Popis/Citace) nebo vrátit 'ŽÁDNÉ NÁVRHY'." reels_result = call_gpt(reels_prompt, system_message=reels_system_message) print(f"Raw Reels Output from GPT:\n---\n{reels_result}\n---") # Validation and assignment (remains the same) 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 : reels_output_display = reels_result.strip() reels_for_zip = reels_output_display print("Reels OK."); gr.Info("Návrhy na Reels vygenerovány.") elif "ŽÁDNÉ NÁVRHY" in reels_result: reels_output_display = "Nebyly nalezeny žádné vhodné úseky pro Reels podle zadaných kritérií." print(reels_output_display); gr.Info(reels_output_display) else: reels_output_display = reels_result if reels_result.startswith("Chyba:") else "Generování Reels selhalo nebo vrátilo neočekávaný formát." print(f"Reels output unexpected: {reels_output_display[:200]}..."); gr.Warning(reels_output_display) if not reels_for_zip and reels_result and not reels_result.startswith("Chyba:"): reels_for_zip = reels_result 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) else: reels_output_display = "Nelze generovat Reels (chybí platný editovaný přepis)." if not reels_for_zip: reels_for_zip = reels_output_display # <<< End of Updated REELS Block >>> # --- Final Output Prep --- progress(0.9, desc="Formátování výstupu...") if chapters_parsed_list and edited_transcript_for_state and not edited_transcript_for_state.startswith("Chyba:"): print("Formatting transcript with generated chapters...") formatted_transcript_w_chapters_output = format_transcript_with_chapters(edited_transcript_for_state, chapters_parsed_list, audio_duration) print("Formatted transcript with chapters prepared.") elif edited_transcript_for_state and not edited_transcript_for_state.startswith("Chyba:"): formatted_transcript_w_chapters_output = edited_transcript_for_state print("Chapters not available, displaying plain edited transcript.") else: formatted_transcript_w_chapters_output = edited_transcript_for_state progress(1.0, desc="Hotovo!"); print(f"Processing OK (Source: {input_source})."); gr.Info("Zpracování dokončeno.") # Return structure updated for display and state return formatted_transcript_w_chapters_output, chapters_output_display, reels_output_display, \ edited_transcript_for_state, context_for_state, segments, chapters_for_zip, reels_for_zip except ValueError as ve: error_message = f"Chyba vstupu: {ve}"; print(error_message); gr.Error(error_message); return "", "", "", "", [], "", "", [] 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, "", "", "", [], "", "", [] # --- KONEC KÓDU PRO process_input --- # --- Gradio Interface Definition --- theme = gr.themes.Default(primary_hue=gr.themes.colors.blue, secondary_hue=gr.themes.colors.sky) with gr.Blocks(theme=theme, title="WhisperBitch v2.4 (Timed Chapters)") as demo: # <<< CHANGE: Updated Title and Info Text >>> gr.Markdown("# 🧠 WhisperBitch v2.4", elem_id="app-title") gr.Markdown("Zpracování audia (Whisper) nebo JSON segmentů. Generuje časované kapitoly, návrhy Reels, článek, SEO, titulky etc.", elem_id="app-subtitle") # State variables (remain the same, but content interpretation changes slightly) transcript_state = gr.State(value="") # Stores CLEAN edited transcript context_state = gr.State(value="") segments_state = gr.State(value=[]) # Stores segments (with PRECISE times from Whisper/JSON) chapters_state = gr.State(value="") # Stores chapter list WITH times (GPT generated) reels_state = gr.State(value="") # Stores reels suggestions WITH times (GPT generated) article_state = gr.State(value="") srt_path_state = gr.State(value=None) vtt_path_state = gr.State(value=None) # --- UI Layout --- with gr.Row(): # --- Input Column --- with gr.Column(scale=1, min_width=350): gr.Markdown("### 1. Vstup") with gr.Tabs(): with gr.TabItem("🎤 Audio"): audio_input = gr.Audio(type="filepath", label="Nahrát audio (max ~25MB)", sources=["upload", "microphone"]) with gr.TabItem("📊 Segmenty (JSON)"): segment_json_input = gr.File(label="Nahrát JSON segmenty (.json)", file_types=[".json"]) gr.Markdown("Formát: `[{\"timestamp\": \"HH:MM:SS,ms-...\", ...}]`") gr.Markdown("### 2. Kontext (nepovinné)") description_input = gr.Textbox(label="Popis / Téma", lines=3) keywords_input = gr.Textbox(label="Klíčová slova", lines=3) submit_button = gr.Button("🚀 Zpracovat Vstup", variant="primary", elem_id="submit-button") # --- Output Column --- with gr.Column(scale=2, min_width=600): gr.Markdown("### 3. Výstupy") # <<< CHANGE: Main output now includes chapters again >>> edited_output_formatted = gr.Textbox(label="✅ Upravený přepis s kapitolami (CZ)", lines=15, interactive=False, show_copy_button=True) with gr.Row(): # <<< CHANGE: Labels updated >>> chapters_output = gr.Textbox(label="🎬 Kapitoly pro YouTube (CZ)", lines=7, interactive=False, show_copy_button=True, scale=1) reels_output = gr.Textbox(label="🎬 Reels / TikTok návrhy (CZ)", lines=7, interactive=False, show_copy_button=True, scale=1) # --- Optional Accordions --- (Article remains the same) with gr.Accordion("📰 Generování článku (volitelné)", open=True): # ... (article UI remains the same) ... article_extra_prompt_input = gr.Textbox(label="⭐ Extra pokyny pro článek", lines=2) generate_article_button = gr.Button("✍️ Vygenerovat článek", variant="primary") article_output_display = gr.Textbox(label="Článek (návrh v CZ)", lines=20, interactive=False, show_copy_button=True) with gr.Accordion("📺 Generování titulků (volitelné)", open=False): gr.Markdown("Generuje titulky s **původními přesnými časy** (z audia/JSONu) a **nově editovaným textem**.", elem_id="subs-info") # ... (SRT/VTT buttons remain the same) ... with gr.Row(): generate_srt_button = gr.Button("Generovat .SRT", variant="secondary") generate_vtt_button = gr.Button("Generovat .VTT", variant="secondary") with gr.Row(): srt_output_ondemand = gr.File(label="SRT Titulky ke stažení", interactive=False) vtt_output_ondemand = gr.File(label="VTT Titulky ke stažení", interactive=False) # --- Download Button --- gr.Markdown("### 4. Stažení") download_button = gr.Button("⬇️ Stáhnout vše (.zip)", variant="primary") download_file_output = gr.File(label="ZIP Archiv ke stažení", interactive=False) # --- Event Handling --- # <<< CHANGE: Updated outputs for process_input >>> submit_button.click( fn=process_input, inputs=[ audio_input, segment_json_input, description_input, keywords_input ], outputs=[ edited_output_formatted, # Textbox: Formatted transcript with chapters chapters_output, # Textbox: Timed Chapters list for display reels_output, # Textbox: Timed Reels list for display transcript_state, # State: Stores CLEAN edited transcript context_state, # State: Stores context segments_state, # State: Stores PRECISE segments (Whisper/JSON) chapters_state, # State: Stores timed chapter list for ZIP reels_state # State: Stores timed reels list for ZIP ], show_progress="full" ) # Other handlers remain the same 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") generate_srt_button.click(fn=generate_srt_file, inputs=[segments_state], outputs=[srt_output_ondemand, srt_path_state], show_progress="minimal") generate_vtt_button.click(fn=generate_vtt_file, inputs=[segments_state], outputs=[vtt_output_ondemand, vtt_path_state], show_progress="minimal") # <<< CHANGE: Pass formatted transcript to ZIP function >>> download_button.click( fn=create_download_zip, inputs=[ edited_output_formatted, # Pass the transcript with chapters inserted chapters_state, reels_state, srt_path_state, vtt_path_state, article_state ], outputs=[download_file_output], show_progress="minimal" ) # --- Launch --- if __name__ == "__main__": if not client: print("\n!!! KRITICKÁ CHYBA: OpenAI klient není inicializován... !!!\n") else: print("\nOpenAI client OK. Starting Gradio...") demo.launch(share=False)