o
    h#                  
   @   s   d Z ddlZddlmZmZmZ ddlmZ ddlZddl	m
Z
 ddlmZ ddlZdd Ze Zed	kr9ed
dejddddejdddejdddZdddddddddddddddd d!dd"d#dd$d%dd&ZG d'd( d(ZdS ))zV
LOCAL GPU IMAGE GENERATOR - GPU OPTIMIZED
==========================================
    N)StableDiffusionXLPipelineStableDiffusionPipelineDPMSolverMultistepScheduler)Image)BytesIO)datetimec                   C   s   t j s$td tdt j  tdt jj  td td dS td tdt j  tdt jj  td	t jd
  tdt jd
jd dd dS )Nu   ❌ CUDA not available!z   PyTorch version: z   CUDA compiled version: u    
💡 Install PyTorch with CUDA:zS   pip install torch torchvision --index-url https://download.pytorch.org/whl/cu118cpuu   ✅ CUDA is available!z   CUDA version: z   GPU: r   z	   VRAM:    @z.1fz GBcuda)	torchr
   is_availableprint__version__versionget_device_nameget_device_propertiestotal_memory r   r   J/var/www/eduai.edurigo.com/generate_image/testing/local_image_generator.pydetect_device   s   
 r   r   zgGPU not detected! This application requires CUDA-enabled GPU.
Please install PyTorch with CUDA support.z(stabilityai/stable-diffusion-xl-base-1.0fp16)   r   )repo_iddtypevariantrecommended_sizezrunwayml/stable-diffusion-v1-5)   r   )r   r   r   z'SG161222/Realistic_Vision_V6.0_B1_noVAE)r   i   )sdxlsd15	realisticzjphotorealistic, 8k uhd, high quality, detailed, professional photography, sharp focus, dslr, soft lightingzEcartoon, anime, painting, sketch, low quality, blurry, ugly, deformed)positivenegativezU3d render, octane render, unreal engine 5, ray tracing, volumetric lighting, detailedz2d, cartoon, flat, low qualityzCcartoon style, disney pixar, animated, vibrant colors, professionalz%realistic photo, dark, ugly, deformedzPcomic book style, graphic novel, bold lines, vibrant colors, dynamic compositionzphoto, blurry, low qualityz?anime style, manga, studio quality, clean lines, vibrant colorsz!realistic, photo, western cartoonzUcinematic lighting, film scene, dramatic, professional cinematography, depth of fieldz"flat lighting, low quality, boringzIfantasy art, magical, epic, detailed, concept art, trending on artstationzmodern, realistic, low qualityz4cyberpunk, neon lights, futuristic, sci-fi, detailedzfantasy, medieval, low quality)r   3dcartoonisticcomicanime	cinematicfantasy	cyberpunkc                   @   s   e Zd ZdZdd ZdedefddZded	efd
dZded	edede	de	f
ddZ
ded	edede	de	de	fddZdd ZdS )LocalImageGeneratorz/Handles model loading and GPU image generation.c                 C   s   d | _ d | _td d S )Nu-   ✅ Local Image Generator initialized on GPU.)pipelinecurrent_modelr   )selfr   r   r   __init__c   s   zLocalImageGenerator.__init__
model_namereturnc              
   C   sh  | j |kr| jrtd| d dS | jr)td | `t  tj  tj  t	
|t	d }td| d td z\|dkrDtnt}|j|d	 |d
 d|
dd| _t| jjj| j_| jt| _| j  z| j  td W n ty   td Y nw || _ tdt| jj j  W dS  ty } ztd|  W Y d}~dS d}~ww )z4Load model to GPU memory, reusing if already loaded.u   ℹ️ Model 'z' already loaded on GPU.Tu(   🧹 Clearing previous model from GPU...r   u   📦 Loading model: z to GPUu+   ⏳ First load may take up to 60 seconds...r   r   r   )torch_dtypeuse_safetensorsr   u*   ✅ xformers enabled for faster inference.u8   ℹ️ xformers not available, using standard attention.u   ✅ Model loaded on: u   ❌ Model load failed: NF)r+   r*   r   gccollectr   r
   empty_cachesynchronizeMODEL_CONFIGSgetr   r   from_pretrainedr   from_config	schedulerconfigtoDEVICEenable_attention_slicing*enable_xformers_memory_efficient_attention	Exceptionnextunet
parametersdevice)r,   r.   cfgpipeline_classer   r   r   
load_modelh   sN   



zLocalImageGenerator.load_modelpromptcategoryc                 C   s.   t | t d }| d|d  |d fS )z1Add style-specific positive and negative prompts.r   z, r    r!   )CATEGORY_STYLESr7   lower)r,   rI   rJ   styler   r   r   enhance_prompt   s   z"LocalImageGenerator.enhance_promptwidthheightc              
   C   s(  |  |sdS | ||\}}|dkrdnd}|| d | | }|| d | | }td| d| d|  z<tj  t  | j||d	d
||d}	W d   n1 sXw   Y  |	jd }
t	 }|
j
|dd td | W S  ty } ztd|  tj  W Y d}~dS d}~ww )z4Generate a single image on GPU and return its bytes.Nr      @      u!   
🎨 Generating on GPU | Model: z | x   g      @)rI   negative_promptnum_inference_stepsguidance_scalerO   rP   r   PNG)formatu'   ✅ Image generated successfully on GPUu   ❌ Generation error: )rH   rN   r   r   r
   r4   inference_moder*   imagesr   savegetvaluer@   )r,   rI   rJ   r.   rO   rP   enhanced_promptrV   multipleresultimagebufferrG   r   r   r   generate_single_image   s<   






z)LocalImageGenerator.generate_single_imageimage_countc              	   C   s   g }t |D ]E}td|d  d| d | |||||}	|	du r#q| d| dt ddd  d|d  }
t|	d	}|	|
|d
 q|S )z'Generate multiple base64 images on GPU.u   
📸 Generating image rS   /z on GPUN_z%Y%m%d_%H%M%S_%fzutf-8)namebase64)
ranger   rd   r   nowstrftimerj   	b64encodedecodeappend)r,   rI   rJ   r.   rO   rP   re   r\   i	img_bytes
image_name
base64_imgr   r   r   generate_multiple_images   s   0
z,LocalImageGenerator.generate_multiple_imagesc                 C   s   i }t j r.t jdtt jdjd dtt jdd dtt jdd dd}dt	t j | j
t jt jjd|S )zGPU and model health check.r   r	      )gpu_namevram_total_gbvram_allocated_gbvram_reserved_gbhealthy)statusrD   gpu_availabler+   pytorch_versioncuda_version)r   r
   r   r   roundr   r   memory_allocatedmemory_reservedr=   r+   r   r   )r,   gpu_infor   r   r   check_health   s    

z LocalImageGenerator.check_healthN)__name__
__module____qualname____doc__r-   strboolrH   rN   intrd   ru   r   r   r   r   r   r)   `   s<    8
*
r)   )r   r   	diffusersr   r   r   PILr   rj   ior   r   r2   r   r=   RuntimeErrorfloat16r6   rK   r)   r   r   r   r   <module>   sl    #