o
    Ch                     @   s~   d Z ddlZddlmZmZ ddlmZmZ ddlm	Z	 ddl
Z
ddlmZ ddlZejejd eeZG dd	 d	ZdS )
u  
PROFESSIONAL VIDEO GENERATOR (LOCAL & OPEN SOURCE)
====================================================
Features:
✅ 100% FREE & Open Source (runs on your hardware)
✅ State-of-the-art Stable Video Diffusion model
✅ High-quality, coherent video generation
✅ Full privacy and control, no external APIs
✅ Optimized for consumer-grade GPUs (>= 12GB VRAM recommended)
✅ Production-ready local inference engine

Author: Professional AI Solutions Architect
Date: 2024
    N)StableVideoDiffusionPipelineStableDiffusionXLPipeline)
load_imageexport_to_video)Image)Path)levelc                	   @   s4   e Zd ZdZdd Zddedededefd	d
ZdS )ProfessionalVideoGeneratorz
    Video generation using a local, self-hosted Stable Video Diffusion model.
    This approach provides maximum control, privacy, and eliminates API dependencies.
    c              
   C   s   t j s	tdd| _td| _| jjdd d| _t	
d zDtjdt jd	d
| _| j  tjdt jd	d
| _| j| j| _t	
d t	
dt jd  t	
d t	
d| j d W dS  tyy } z	t	d|   d}~ww )z
        Initializes the video generation pipelines.
        
        This is a heavy operation and should only be done once at application startup.
        It will download models from Hugging Face on the first run.
        uF   ❌ CUDA is not available. A GPU is required for this video generator.cudagenerated_videosT)exist_okr   z@ M odel Loading: This may take a few minutes on the first run...z-stabilityai/stable-video-diffusion-img2vid-xtfp16)torch_dtypevariantzstabilityai/sdxl-turbou6   ✅ ProfessionalVideoGenerator initialized (Local SVD)z   GPU: zR   Models: SDXL-Turbo (for initial image) + Stable Video Diffusion (for animation)z   Output directory: /u{   ❌ Failed to load models. Ensure you have a stable internet connection for the first download and sufficient VRAM. Error: N)torchr
   is_availableRuntimeErrordevicer   
output_dirmkdirgeneration_countloggerinfor   from_pretrainedfloat16svd_pipeenable_model_cpu_offloadr   txt2img_pipetoget_device_name	Exceptionerror)selfe r%   F/var/www/eduai.edurigo.com/image_generation/testing/video_generator.py__init__!   s:   





z#ProfessionalVideoGenerator.__init__16:9promptstyleaspect_ratioreturnc              
   C   s  |  j d7  _ t }td| j   td|dd  d td|  ztd | d	| }d
\}}| j|dd||djd }td |d
}	| j|	dddddjd }
td t	t d }d| d}| j
| }t|
t|dd t | }| jd }td td|dd td |d!d" td#|  d$t|||||d%W S  ty } z%ddl}d&t| }td'|  t|  d(|d)W  Y d}~S d}~ww )*aK  
        Generates a video from a text prompt.
        
        Workflow:
        1. Generate a high-quality initial image from the prompt using SDXL Turbo.
        2. Animate the image into a video using Stable Video Diffusion.
        
        Args:
            prompt (str): Text description for the video.
            style (str): Visual style (e.g., 'realistic', 'cinematic', 'animated').
            aspect_ratio (str): The desired aspect ratio. Note: SVD is optimized for 16:9.

        Returns:
            dict: Result with video path and metadata, or an error message.
           u   
🎬 Generating Video #z   Prompt: NP   z...z
   Style: u'      ⏳ 1/3: Generating initial image...z, )i   i@     g        )r)   num_inference_stepsguidance_scalewidthheightr   u(      ⏳ 2/3: Animating frames with SVD...      g{Gz?   )decode_chunk_sizemotion_bucket_idnoise_aug_strength
num_framesu#      ⏳ 3/3: Exporting video file...i  video_z.mp4   )fpsi   u      ✅ SUCCESSu      ⏱️  Time: z.1fsu      📊 Size: z.2fz MBu      💾 Saved: T)success
video_pathvideo_filenamer)   r*   generation_timezVideo generation failed: u      ❌ F)r?   r"   )r   timer   r   r   imagesresizer   framesintr   r   strstatst_sizer!   	tracebackr"   
format_exc)r#   r)   r*   r+   
start_timefull_promptimage_widthimage_heightinitial_imageimagerF   	timestamprA   r@   rB   video_size_mbr$   rK   	error_msgr%   r%   r&   generate_videoO   sn   

	

	

	z)ProfessionalVideoGenerator.generate_videoN)r(   )__name__
__module____qualname____doc__r'   rH   dictrV   r%   r%   r%   r&   r	      s     .r	   )rZ   r   	diffusersr   r   diffusers.utilsr   r   PILr   rC   pathlibr   loggingbasicConfigINFO	getLoggerrW   r   r	   r%   r%   r%   r&   <module>   s    
