Update app.py
Browse files12 unmodified lines1314151617181128 unmodified lines114711481149115011511152115311541155115611571158115933 unmodified lines11931194119511961197119811991200120112028 unmodified lines1211121212131214121512161217121812191220122112226 unmodified lines1229123012311232123312341235166 unmodified lines1402140314041405140614078 unmodified lines14161417141814191420142114224 unmodified lines142714281429143014311432143342 unmodified lines1476147714781479148014814 unmodified lines148614871488148914901491149214931494149537 unmodified lines1533153415351536153715381539154016 unmodified lines1557155815591560156115628 unmodified lines157115721573157415751576157712 unmodified linesimport gcfrom huggingface_hub import hf_hub_downloadimport threading# ZeroGPU-compatible importsfrom transformers import AutoTokenizer, AutoModelForCausalLM, pipeline1128 unmodified lines"scenes": [],"style": "Model loading failed"}return None, error_info, "β Failed to load AI models", [], []# Step 1: Generate professional scriptprint("π Creating professional script structure...")script_data = self.generate_professional_script(script)print(f"β Script generated with {len(script_data['scenes'])} scenes")# Step 2: Generate high-quality charactersprint("π Creating professional character designs...")character_images = self.generate_professional_character_images(script_data['characters'])33 unmodified lineschar_files = list(character_images.values()) if character_images else []bg_files = list(background_images.values()) if background_images else []return final_video, script_data, f"β Professional cartoon film generated successfully! ({file_size:.1f} MB)", char_files, bg_fileselse:print("β οΈ Video merging failed")return None, script_data, "β οΈ Video merging failed", [], []else:print("β No videos to merge - video generation failed")print("π Creating emergency fallback video...")8 unmodified linesdownload_info = self.create_download_url(emergency_video, "emergency_fallback_video")print(f"β Emergency fallback video created")print(download_info)return emergency_video, script_data, f"β οΈ Emergency fallback video created ({file_size:.1f} MB)", [], []else:return None, script_data, "β No videos generated - all methods failed", [], []except Exception as e:print(f"β Emergency fallback also failed: {e}")return None, script_data, "β No videos generated - all methods failed", [], []except Exception as e:print(f"β Generation failed: {e}")6 unmodified lines"scenes": [],"style": "Error occurred during generation"}return None, error_info, f"β Generation failed: {str(e)}", [], []def _create_lightweight_animated_video(self, scene: Dict, character_images: Dict, background_images: Dict) -> str:"""Create lightweight animated video with character/background compositing"""166 unmodified linesprint(f"β οΈ Character overlay failed: {e}")return background# Initialize professional generatorgenerator = ProfessionalCartoonFilmGenerator()8 unmodified lines"scenes": [],"style": "Please enter a script"}return None, empty_response, "β Please enter a script", [], []# Check if another generation is in progressif not generation_lock.acquire(blocking=False):4 unmodified lines"scenes": [],"style": "Please wait for current generation to complete"}return None, busy_response, "β³ Generation already in progress - please wait", [], []try:return generator.generate_professional_cartoon_film(script)42 unmodified lines- **Cinematic backgrounds** with professional lighting- **Advanced animation effects** based on scene mood- **4K video output** with 24fps cinematic quality**π― Perfect for:**- Content creators seeking professional results4 unmodified lines---**β οΈ Current Status:**- β **Storage System:** Fixed for Hugging Face Spaces- β οΈ **FLUX Models:** Require authentication token (using Stable Diffusion fallback)- β οΈ **Open-Sora:** Using static video fallback for stability- β **File Downloads:** Available through Gradio galleries below**π‘ To unlock full FLUX quality:**1. Get token from [Hugging Face Settings](https://huggingface.co/settings/tokens)37 unmodified lines**β οΈ Important Notes:**- Only **ONE generation at a time** - multiple clicks will be queued- **Processing takes 8-12 minutes** - please be patient- **Files auto-download** through galleries below- **Storage fixed** for Hugging Face Spaces compatibility""")video_output = gr.Video(16 unmodified linesallow_preview=True)status_output = gr.Textbox(label="π Generation Status",lines=38 unmodified linesgenerate_btn.click(fn=create_professional_cartoon_film,inputs=[script_input],outputs=[video_output, script_details, status_output, character_gallery, background_gallery],show_progress=True)12 unmodified lines13141516171819201128 unmodified lines1149115011511152115311541155115611571158115911601161116211631164116533 unmodified lines11991200120112021203120412051206120712081209121012111212121312141215121612171218121912208 unmodified lines12291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212536 unmodified lines1260126112621263126412651266166 unmodified lines14331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814998 unmodified lines15081509151015111512151315144 unmodified lines151915201521152215231524152542 unmodified lines156815691570157115721573157415754 unmodified lines1580158115821583158415851586158715881589159037 unmodified lines16281629163016311632163316341635163616 unmodified lines16531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616778 unmodified lines168616871688168916901691169212 unmodified linesimport gcfrom huggingface_hub import hf_hub_downloadimport threadingimport datetimeimport time# ZeroGPU-compatible importsfrom transformers import AutoTokenizer, AutoModelForCausalLM, pipeline1128 unmodified lines"scenes": [],"style": "Model loading failed"}return None, error_info, "β Failed to load AI models", [], [], None, None, []# Step 1: Generate professional scriptprint("π Creating professional script structure...")script_data = self.generate_professional_script(script)print(f"β Script generated with {len(script_data['scenes'])} scenes")# Save script to fileprint("π Saving script to file...")script_file_path = self.save_script_to_file(script_data, script)# Step 2: Generate high-quality charactersprint("π Creating professional character designs...")character_images = self.generate_professional_character_images(script_data['characters'])33 unmodified lineschar_files = list(character_images.values()) if character_images else []bg_files = list(background_images.values()) if background_images else []# Create download links for all filesall_files = {}if script_file_path:all_files["script"] = script_file_pathif final_video:all_files["video"] = final_videoall_files.update(character_images)all_files.update(background_images)download_links = self.create_download_links(all_files)script_file, video_file = self.get_download_files(all_files)return final_video, script_data, f"β Professional cartoon film generated successfully! ({file_size:.1f} MB)", char_files, bg_files, script_file, video_file, download_linkselse:print("β οΈ Video merging failed")return None, script_data, "β οΈ Video merging failed", [], [], None, None, []else:print("β No videos to merge - video generation failed")print("π Creating emergency fallback video...")8 unmodified linesdownload_info = self.create_download_url(emergency_video, "emergency_fallback_video")print(f"β Emergency fallback video created")print(download_info)# Create download links for emergency filesall_files = {}if script_file_path:all_files["script"] = script_file_pathif emergency_video:all_files["video"] = emergency_videoall_files.update(character_images)all_files.update(background_images)download_links = self.create_download_links(all_files)script_file, video_file = self.get_download_files(all_files)return emergency_video, script_data, f"β οΈ Emergency fallback video created ({file_size:.1f} MB)", [], [], script_file, video_file, download_linkselse:return None, script_data, "β No videos generated - all methods failed", [], [], None, None, []except Exception as e:print(f"β Emergency fallback also failed: {e}")return None, script_data, "β No videos generated - all methods failed", [], [], None, None, []except Exception as e:print(f"β Generation failed: {e}")6 unmodified lines"scenes": [],"style": "Error occurred during generation"}return None, error_info, f"β Generation failed: {str(e)}", [], [], None, None, []def _create_lightweight_animated_video(self, scene: Dict, character_images: Dict, background_images: Dict) -> str:"""Create lightweight animated video with character/background compositing"""166 unmodified linesprint(f"β οΈ Character overlay failed: {e}")return backgrounddef save_script_to_file(self, script_data: Dict[str, Any], original_script: str) -> str:"""Save script data to a JSON file in tmp folder"""try:# Create a comprehensive script file with all datascript_file_data = {"original_script": original_script,"generated_script": script_data,"timestamp": str(datetime.datetime.now()),"version": "1.0"}# Save to tmp folderscript_path = f"{self.output_dir}/cartoon_script_{int(time.time())}.json"with open(script_path, 'w', encoding='utf-8') as f:json.dump(script_file_data, f, indent=2, ensure_ascii=False)if os.path.exists(script_path):file_size = os.path.getsize(script_path) / 1024 # KBprint(f"π Script saved: {script_path} ({file_size:.1f} KB)")return script_pathelse:print(f"β Failed to save script: {script_path}")return Noneexcept Exception as e:print(f"β Error saving script: {e}")return Nonedef create_download_links(self, files_dict: Dict[str, str]) -> List[Dict[str, str]]:"""Create download links for files"""download_links = []for file_type, file_path in files_dict.items():if os.path.exists(file_path):file_name = os.path.basename(file_path)file_size = os.path.getsize(file_path) / (1024*1024) # MBdownload_links.append({"name": file_name,"path": file_path,"size": f"{file_size:.1f} MB","type": file_type})return download_linksdef get_download_files(self, files_dict: Dict[str, str]) -> tuple:"""Get file objects for Gradio download components"""script_file = Nonevideo_file = Nonefor file_type, file_path in files_dict.items():if os.path.exists(file_path):if file_type == "script":script_file = file_pathelif file_type == "video":video_file = file_pathreturn script_file, video_file# Initialize professional generatorgenerator = ProfessionalCartoonFilmGenerator()8 unmodified lines"scenes": [],"style": "Please enter a script"}return None, empty_response, "β Please enter a script", [], [], None, None, []# Check if another generation is in progressif not generation_lock.acquire(blocking=False):4 unmodified lines"scenes": [],"style": "Please wait for current generation to complete"}return None, busy_response, "β³ Generation already in progress - please wait", [], [], None, None, []try:return generator.generate_professional_cartoon_film(script)42 unmodified lines- **Cinematic backgrounds** with professional lighting- **Advanced animation effects** based on scene mood- **4K video output** with 24fps cinematic quality- **π Script downloads** - Full JSON with story analysis- **π File management** - All files saved in /tmp with download links**π― Perfect for:**- Content creators seeking professional results4 unmodified lines---**β οΈ Current Status:**- β **Storage System:** Fixed for Hugging Face Spaces (/tmp folder)- β **Script Downloads:** JSON files with complete story analysis- β **File Downloads:** Direct download buttons for all generated content- β οΈ **FLUX Models:** Require authentication token (using Stable Diffusion fallback)- β οΈ **Open-Sora:** Using static video fallback for stability**π‘ To unlock full FLUX quality:**1. Get token from [Hugging Face Settings](https://huggingface.co/settings/tokens)37 unmodified lines**β οΈ Important Notes:**- Only **ONE generation at a time** - multiple clicks will be queued- **Processing takes 8-12 minutes** - please be patient- **Files saved in /tmp folder** with download links below- **Script saved as JSON** with full story analysis- **Images and videos** available for download""")video_output = gr.Video(16 unmodified linesallow_preview=True)# Add download buttons for scripts and other filesscript_download = gr.File(label="π Download Script (JSON)",file_types=[".json"],visible=True)video_download = gr.File(label="π¬ Download Video (MP4)",file_types=[".mp4"],visible=True)# Download links displaydownload_links_output = gr.JSON(label="π₯ Download Links",visible=True)status_output = gr.Textbox(label="π Generation Status",lines=38 unmodified linesgenerate_btn.click(fn=create_professional_cartoon_film,inputs=[script_input],outputs=[video_output, script_details, status_output, character_gallery, background_gallery, script_download, video_download, download_links_output],show_progress=True)
app.py+129-14