o
    Z_h                  
   @   sH  d Z ddlZddlZddlZddlZddlZddlZddlmZ ddl	m	Z	 ddl
mZ ddlZddlZzddlmZ W n& eyb   ed ddlZeejdd	d
dg ddlmZ ed Y nw ed ed ed ed ed e  dZdZdZdZdZdg dddddg dddddg dd d!dd"g d#d$d%dd&g d'd(d)dd*g d+d,d-dd.Zi d/d0d1d0d2d0d3d0d4d0d5d6d7d6d8d6d9d6d:d6d;d<d=d<d>d<d?d<d@d<dAd<dBdCi dDdCdEdCdFdCdGdHdIdHdJdHdKdLdMdLdNdLdOdLdPdLdQdLdRdLdSdLdTdLdUdLdVdLi dWdLdXdLdYdLdZdLd[dLd\dLd]dLd^dLd_dLd`dLdad0dbd6dcd6ddd0ded0dfd6dgd6i dhd0did0djd0dkdLdld0dmd0dnd0dod0dpd0dqdLdrdLdsdLdtdLdudLdvdLdwdLdxdLi dydCdzdLd{dLd|dLd}dLd~dLdd0dd0dd<dd<dd0dd6dd6dd<dd6dd6dd0i dd0dd0dd0dd6dd6dd6ddLddLddLddLddLddLdd0ddLddLddLddLi ddLddLddLddLdd0ddLddHddLdd0ddLddLdd0dd0dd0dd0dd0dd6d6d6dHdZi dZdd[dd^dd{ddUddTddvddaddhddlddfddddddqddtddzdddd_diZdd Zdd ZddĄ ZddƄ Z ddȄ Z!G ddʄ dʃZ"dd̄ Z#dd΄ Z$ddЄ Z%dd҄ Z&ddԄ Z'e(dkre'  dS dS )u  
PROFESSIONAL IMAGE GENERATOR - ALL CATEGORIES VERSION
======================================================
Features:
✅ ALL Category Types Supported - No Restrictions
✅ Auto Model Selection Based on Category Keywords
✅ 100+ Category Types Enabled
✅ Intelligent Category Mapping
✅ 1920x1080 Full HD Resolution
✅ Professional Quality Output

Author: Professional Image Generation System
Date: 2025
    N)Path)datetime)BytesIO)Imageu   📦 Installing Pillow...z-mpipinstallpillowu   ✅ Pillow installed!
P================================================================================z:PROFESSIONAL IMAGE GENERATOR - ALL CATEGORIES VERSION V3.0uH   ✅ Full HD 1920x1080 | ALL Categories Supported | Smart Model Selectionz%https://image.pollinations.ai/prompt/professional_imagesi  i8  Tzflux-realism)	realisticphotorealistichyperrealisticphotophotographyzultra photorealistic, professional photography, extremely detailed, sharp focus, perfect lighting, 8K UHD, RAW photo, high quality, film grain, Fujifilm XT3, professional color grading, award winning photographyzWcartoon, anime, illustration, painting, drawing, art, sketch, 3d render, deformed, ugly)modelkeywordssuffixnegativezflux-3d)3dcgirenderrendered	3d-renderoctanez3D render, octane render, unreal engine 5, ray tracing, ultra detailed 3D model, CGI, volumetric lighting, ambient occlusion, subsurface scattering, physically based rendering, 8K resolution, studio lightingzA2d, flat, cartoon, anime, painting, sketch, low poly, low qualityzflux-cablyai)cartoonisticcartoonanimated	animationdisneypixartoonzcartoon style, disney pixar style, animated, colorful, clean lines, vibrant colors, professional animation, studio quality, character design, expressive, polished, high quality cartoonz7realistic, photo, 3d render, dark, gritty, horror, uglyzflux-cartoon)comic
comic-bookgraphic-novelpop-artgraphiccomicszcomic book style, comic art, graphic novel, bold lines, vibrant colors, dynamic composition, pop art, professional comic illustration, ink and color, halftone dotsz0realistic, photo, 3d render, blurry, low qualityz
flux-anime)animemangaanime-stylemanga-stylezjapanese-animezanime style, manga art, japanese animation, cel shaded, vibrant colors, expressive eyes, detailed hair, professional anime artwork, studio quality, beautiful lightingz<realistic, photo, western cartoon, 3d render, ugly, deformedflux)	cinematiccinematic-shotmoviefilm	hollywoodepiczcinematic shot, movie scene, cinematic lighting, epic composition, dramatic atmosphere, film photography, anamorphic lens, depth of field, color graded, professional production, blockbuster movie quality, 35mm film, IMAX qualityz2amateur, low quality, snapshot, boring compositionr   r   r   r!   r'   r,   r   r   r   r   r   zprofessional-photographyr   r   r   r   zoctane-renderzunreal-enginer   r   r   r   r   r   r    r"   r!   r#   r$   r&   r(   r'   r)   r*   r.   r,   r/   r0   r1   r-   artisticartpaintingoil-painting
watercolorzdigital-artzdigital-paintingzconcept-artillustrationfantasysci-fizscience-fiction
futuristic	cyberpunk	steampunkspaceportrait	characterzcharacter-designfaceheadshotarchitecturalarchitecture	landscapenature	cityscapeenvironmentproductzproduct-photography
commercialadvertising	marketingabstractmoderncontemporary
minimalist	geometricsketchpencildrawingzline-artdarkhorrorgothicnoirdramaticvintageretro80s90sz
old-schoolgamezgame-art	pixel-artzlow-polyvoxelfashionbeautyglamour	editorialtexturematerialpbrimpressionistexpressionistsurreal
surrealismcubistbaroquerenaissancemoodyatmosphericdreamyetherealmysticalmagicalmedievalancientz
modern-dayzpost-apocalypticjapanesechinesekoreanwesterneasternanimalwildlifefoodinteriorexteriorvehicle)weaponrobotmechaz9magical, mystical, enchanted, fantasy world, epic fantasyz;futuristic, advanced technology, space age, sci-fi elementszEneon lights, cyberpunk aesthetic, futuristic city, blade runner stylez8dark, eerie, creepy, horror atmosphere, dramatic shadowsz8watercolor painting, soft colors, artistic brush strokesz1oil painting style, classical art, museum qualityz7pencil sketch, hand drawn, artistic lines, sketch stylez>professional portrait, studio lighting, shallow depth of fieldz4beautiful landscape, scenic view, nature photographyzIproduct shot, clean background, professional lighting, commercial qualityz@architectural photography, professional composition, clean lineszEfashion photography, haute couture, editorial style, magazine qualityz4vintage style, retro aesthetic, aged look, nostalgicz3abstract art, artistic composition, creative designz4minimalist design, clean composition, simple elegantz1dark atmosphere, moody lighting, dramatic shadowsz.pixel art style, retro gaming, 8-bit aestheticz@steampunk aesthetic, Victorian era, brass and copper, mechanicalc                    s(  |    }|dddd  tv rt  S  tv r S t D ]\}}|d D ]}| v s4 |v r:|    S q*q"t fdddD rIdS t fd	dd
D rVdS t fdddD rcdS t fdddD rpdS t fdddD r}dS t fdddD rdS td|  d dS )z
    Intelligently detect which main category to use based on input
    
    Args:
        category: Input category string
    
    Returns:
        Main category name
     -_r   c                 3       | ]}| v V  qd S N .0wordcategory_normalizedr   T/var/www/eduai.edurigo.com/generate_image/production/pollinations_image_generator.py	<genexpr>T      z'detect_category_type.<locals>.<genexpr>)realr   r   c                 3   r   r   r   r   r   r   r   r   V  r   )r   r   r   r   c                 3   r   r   r   r   r   r   r   r   X  r   )r   animr   r   c                 3   r   r   r   r   r   r   r   r   Z  r   )r!   r(   r!   c                 3   r   r   r   r   r   r   r   r   \  r   )r'   r(   r'   c                 3   r   r   r   r   r   r   r   r   ^  r   )cinemar.   r/   r,   u      ℹ️ Unknown category 'z', using 'cinematic' as default)lowerstripreplaceEXTENDED_CATEGORIESMAIN_CATEGORIESitemsanyprint)categorycategory_lowermain_catconfigkeywordr   r   r   detect_category_type8  s4   
r   c           
      C   s   |   dddd}t|}t| }d}|d }d}|tv r)dt|  }d}| d|  d| | d| }	|d	krD|	d
7 }	|	S |dkrN|	d7 }	|	S |dkrX|	d7 }	|	S |dkrb|	d7 }	|	S |dkrl|	d7 }	|	S |dkrt|	d7 }	|	S )z
    Enhance prompt based on category with intelligent additions
    
    Args:
        prompt: Original user prompt
        category: Selected category
    
    Returns:
        Enhanced prompt string
    r   r   r   zLmasterpiece, best quality, ultra detailed, professional, perfect compositionr    , z>perfect anatomy, perfect perspective, golden ratio compositionr   zB, shot on Canon EOS R5, 85mm lens, f/1.4, professional photographyr   zD, rendered in Octane, global illumination, HDRI lighting, 8K qualityr,   z4, cinematic composition, film grain, anamorphic lensr'   z#, trending on pixiv, studio qualityr   z), Disney animation studios, Pixar qualityr!   z), professional comic artist, Marvel style)r   r   r   r   r   CATEGORY_ENHANCEMENTS)
promptr   r   main_categorycategory_configquality_prefixstyle_suffixextra_enhancement	technicalenhancedr   r   r   enhance_prompt_for_categoryf  s8   
r   c                 C   s   t | }t| ddS )z
    Get negative prompt based on category
    
    Args:
        category: Category name
    
    Returns:
        Negative prompt string
    r   r   )r   r   getr   r   r   r   r   get_negative_prompt  s   
r   c                 C   s   t | }t| d S )z
    Get the best model for a given category
    
    Args:
        category: Category name
    
    Returns:
        Model name
    r   )r   r   r   r   r   r   get_model_for_category  s   
r   c           
      C   sr   t | }ddddddd}||d\}}tt|  d	d
 d}tdd}|| ||  }|| }	|	S )z
    Generate optimized seed based on category and prompt
    
    Args:
        category: Category name
        prompt: Prompt text
    
    Returns:
        Optimized seed value
    )    )r   '  )r   :  )r    N  )r   a  )r   0u  r2   )r   r   N      r   r   )	r   r   inthashlibmd5encode	hexdigestrandomrandint)
r   r   r   seed_rangesmin_seedmax_seedprompt_hashrandom_component	base_seedoptimized_seedr   r   r   get_optimized_seed  s   	 r   c                   @   sN   e Zd ZdZdd Zdd ZdddZdd
dZdddZdd Z	dd Z
dS )ProfessionalImageGeneratorzBProfessional image generation system supporting ALL category typesc                 C   s:   d| _ |   td tdt d td td d S )Nr   u*   ✅ ProfessionalImageGenerator initializedu   📁 Output folder: /u/   🎨 ALL Categories Supported - No Restrictionsu(   🤖 Intelligent Model Selection Enabled)generation_countcreate_output_foldersr   OUTPUT_FOLDERselfr   r   r   __init__  s   z#ProfessionalImageGenerator.__init__c                 C   sf   t t}|jdd t D ]
}|| jdd q|d jdd |d jdd |d jdd dS )z(Create organized output folder structureT)exist_okothermetadatatestsN)r   r   mkdirr   keys)r   	base_pathr   r   r   r   r     s   z0ProfessionalImageGenerator.create_output_foldersNc              
   C   sH  |du rt }|du rt}|  jd7  _|  }t|}|}t||}t|}	t||}
t	 t
j| }||||
ddtt dd}|	rL|	|d< td| j  td|  d|   td	|  td
| d|  td|
  td|dd  d td zet
j||dd}|jdkrtt|j}|jdkr|d}t }|j|dddd |d | }t|d }td td|dd td |W S td |j  td!|jdd   W dS  t
jjy   td" Y dS  t y# } ztd#t|  ddl!}|"  W Y d}~dS d}~ww )$a  
        Generate single image and return bytes for FastAPI
        Accepts ANY category type - no restrictions

        Args:
            prompt: The text prompt
            category: ANY category name (used for prompt enhancement)
            model_name: Specific model to use (flux, nano-banana, turbo)
            width: Image width (default 1920)
            height: Image height (default 1080)

        Returns:
            Image bytes or None if failed
        N   true)widthheightr   seednologoenhancesafenofeednegative_promptu   
🎨 Generating Image #z   Category: u    → Main: z
   Model: z   Resolution: xz	   Seed: z   Prompt: <   z...u$      ⏳ Processing (15-30 seconds)...x   )paramstimeout   RGBPNGd   F)formatqualityoptimizer      u      ✅ SUCCESSu      📊 Size: z.2fz MBu       🎯 Quality: Professional HDu      ❌ API Error: HTTP z   Response: u4      ❌ Timeout: Request took longer than 120 secondsu      ❌ Generation Failed: )#QUALITY_WIDTHQUALITY_HEIGHTr   r   r   r   r   r   r   API_URLrequestsutilsquotestrSAFETY_ENABLEDr   upperr   status_coder   openr   contentmodeconvertsaveseekgetvaluelentext
exceptionsTimeout	Exception	traceback	print_exc)r   r   r   
model_namer   r   r   r   enhanced_promptr   r   urlr   responseimageoutputimage_bytesimage_size_mber  r   r   r   generate_single_image_bytes  st   






z6ProfessionalImageGenerator.generate_single_image_bytesr   c              
   C   s6  g }t |D ]}td|d  d|  | j|||||d}	|	du r,td|d   qt ddd }
t| d	|  	 dd
 }|
 dd }d	| dddddd }| d	| d	|
 d	|d  d	| 	}t|	d}|||d td|  ||d k rtd q|S )a  
        Generate multiple images and return list with names and base64 data

        Args:
            prompt: The text prompt
            category: Category name for enhancement
            model_name: Model to use
            width: Image width
            height: Image height
            image_count: Number of images to generate

        Returns:
            List of dicts with 'name' and 'base64' keys
        u   
📸 Generating image r   r   )r   r   r
  r   r   Nu       ❌ Failed to generate image %Y%m%d_%H%M%S_%fr         ,r   .   zutf-8)namebase64u      ✅ Generated: )ranger   r  r   nowstrftimer   r   r   r   splitjoinr   r   r  	b64encodedecodeappendtimesleep)r   r   r   r
  r   r   image_countimagesir  	timestampr   prompt_wordsprompt_brief
image_namebase64_datar   r   r   generate_multiple_imagesY  s8   $&$
z3ProfessionalImageGenerator.generate_multiple_imagesr+   c              
   C   s  |du rt }|du rt}| |||||}|du rdddS t|}|tv r)|}nd}t ddd }	t	|
  dd }
| dd	 }d
| dddddd }| d
| d
|	 d
|
 d}tt| | }t|d}|| W d   n1 sw   Y  t  | jd|t||t|d||t|| d| t|d t||dd}ttd |dd  }t|d}tj||dd W d   n1 sw   Y  td|  td|  dt|t||dS ) a'  
        Generate image and save to disk

        Args:
            prompt: The text prompt
            category: Category name
            model_name: Model to use
            width: Image width
            height: Image height

        Returns:
            Dictionary with result info
        NFzImage generation failed)successerrorr   r  r  r  r  r   r  r   r     z.pngwb)r*  generation_number)originalr   r   r   r   )r   r   r   
resolutionfile_size_mbr   )generation_infoprompt_datatechnical_detailsr   z.jsonw   )indentu      💾 Saved: u      📄 Metadata: T)r0  pathmetadata_pathr   )r   r   r  r   r   r   r  r  r   r   r   r   r   r!  r   r   r   r   r   write	isoformatr   r   r   r   r  r   jsondumpr   r   )r   r   r   r
  r   r   r  r   folderr*  r   r+  r,  filenameoutput_pathfr   r?  r   r   r   generate_and_save_image  s\   
&

z2ProfessionalImageGenerator.generate_and_save_imagec                 C   s(   dd t  D ttttt  ddS )z.Get information about all supported categoriesc                 S   s.   i | ]\}}||d  | dd|d dqS )r   descriptionr   r   )r   rI  r   r   )r   r  r   r   r   r   
<dictcomp>  s    
zFProfessionalImageGenerator.get_all_categories_info.<locals>.<dictcomp>zdAll category types are supported. Unknown categories will be intelligently mapped to the best model.)main_categoriesextended_categoriestotal_supportedmessage)r   r   r   r  r   r   r   r   get_all_categories_info  s   z2ProfessionalImageGenerator.get_all_categories_infoc                 C   s   t d t dt| d t d t d|  t d g }t|dD ]4\}}t d| dt| d	|  t d
 | ||}|||d |t|k rXt d td q$tdd |D }t d t d t d t d| dt|  t dt||  dt|  t d |S )z
        Test generation with multiple categories
        
        Args:
            prompt: Prompt to use
            categories_list: List of categories to test
        
        Returns:
            List of results
        Q
================================================================================u   🧪 TESTING z CATEGORIESr	   u   📝 Prompt: r   
[r   z] Testing: <------------------------------------------------------------)r   result   
⏳ Waiting 2 seconds...r<  c                 s   s$    | ]}|d   ddrdV  qdS )rT  r0  Fr   NrJ  r   rr   r   r   r     s   " zFProfessionalImageGenerator.test_multiple_categories.<locals>.<genexpr>u   ✅ TEST COMPLETE	Success: zFailed: )r   r  	enumeraterH  r$  r%  r&  sum)r   r   categories_listresultsidxr   rT  
successfulr   r   r   test_multiple_categories  s4   
 z3ProfessionalImageGenerator.test_multiple_categories)NN)NNr   )r+   NN)__name__
__module____qualname____doc__r   r   r  r/  rH  rP  r_  r   r   r   r   r     s    

h
8Nr   c                  C   sV  t d t d t d t } 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dddddg
}g }t|dD ]C\}}t d| dt| d|d    t d|d   t d | j|d |d d}|| |t|k rt d  td! q@t	d"d# |D }t d$ t d% t d t d&| dt|  t d d'S )(zTest most popular categoriesr	   zTESTING POPULAR CATEGORIESz!A beautiful sunset over mountainsr   r   r   zA futuristic robot characterr   zA cute cartoon dog playingr   zA superhero in action poser!   zAn anime girl with blue hairr'   zAn epic battle scener,   zA magical fantasy castler9   zA cyberpunk city at nightr<   zA professional portrait photor?   z A watercolor painting of flowersr7   r   rR  r   ] r   zPrompt: r   rS  rU  r<  c                 s   s     | ]}| d drdV  qdS )r0  Fr   NrJ  rV  r   r   r   r   H  s    z*test_popular_categories.<locals>.<genexpr>rQ  u$   ✅ POPULAR CATEGORIES TEST COMPLETErX  N)
r   r   rY  r  r   rH  r$  r%  r&  rZ  )	generator
test_casesr\  r]  testrT  r^  r   r   r   test_popular_categories   sF   &

ri  c                  C   s:   t d t d t d t } g d}d}| ||}|S )z6Test various category types to demonstrate flexibilityr	   zTESTING ALL CATEGORY TYPES)r   r   r   r!   r'   r,   r9   r:   r<   r7   r6   rR   r?   rE   rI   rC   rV   rZ   r_   ra   z'A majestic dragon in a mystical settingr   r   r_  )rf  test_categoriesr   r\  r   r   r   test_all_category_typesP  s   rl  c               	   C   s   t d t d t d t } dddddddd	dg}t|d
D ]-\}}t d| dt| d|d    | j|d |d d}|t|k rOtd q"t d t d t d dS )z"Quick test with 3 different stylesr	   zQUICK TEST - 3 CATEGORIESzA red sports carr   rd  zA cute robot characterr   zA magical forest scener9   r   rR  r   re  r   r   r<  rQ  u   ✅ QUICK TEST COMPLETEN)r   r   rY  r  r   rH  r%  r&  )rf  rg  r]  rh  rT  r   r   r   
quick_testh  s(   &
rm  c                  C   sJ   t d t d t d t d t d t } g d}d}| ||}|S )z*Test with completely custom category namesr	   zTESTING CUSTOM CATEGORY NAMESz7Testing system's ability to handle any category name...)
zepic-battle-scenezprofessional-headshotzgame-character-designzbook-cover-artzmovie-posterzalbum-coverzt-shirt-designzlogo-designzchildren-book-illustrationzscientific-diagramz"A creative and professional designrj  )rf  custom_categoriesr   r\  r   r   r   test_custom_categories  s   ro  c            
   	   C   s  t d t d t d t d t d t d t d t d t d t d t D ]\} }t d	|   d
|d   q,t d t d t d g d}t d| t d t d t d t d t d t d t d t d t d t d t d t d td }|dkrt  n|dkrt  n|dkrt	  n|dkrt
  n|dkrtd }td }t }||| n|d kr6t }| }t d t d! t d t d"t|d#   |d#  D ]	} t d	|   qt d$t|d%   t|d%  }td&t|d'D ]}	t d(d||	|	d'    qt d)|d*   t d n|d+krAt d, d-S t d. d-S t d t d/ t d0t d1 t d d-S )2z#Main function with interactive menurQ  z5PROFESSIONAL IMAGE GENERATOR - ALL CATEGORIES VERSIONr	   u!   
✅ ALL CATEGORY TYPES SUPPORTEDu0   ✅ NO RESTRICTIONS - ANY CATEGORY NAME ACCEPTEDu   ✅ INTELLIGENT MODEL SELECTIONu   ✅ 100+ CATEGORY MAPPINGSzAVAILABLE MAIN CATEGORIESu     • z: r   zEXAMPLE SUPPORTED CATEGORIES)r   r   r   r!   r'   r,   r9   r:   r<   r7   r6   rR   r?   rE   rV   rZ   r_   ra   rI   rC   r=   rU   r[   rM   rP   r^   r(   r   r   r   z4
...and MANY MORE! System accepts ANY category name.zTESTING MENUu   1️⃣  Quick Test (3 images)u,   2️⃣  Test Popular Categories (10 images)u,   3️⃣  Test All Category Types (20 images)u+   4️⃣  Test Custom Categories (10 images)u!   5️⃣  Custom Single Generationu&   6️⃣  Show All Supported Categoriesu   7️⃣  Exitz
Select option (1-7): 12345z
Enter prompt: zEnter category (any name): 6zALL SUPPORTED CATEGORIESz
Main Categories: rL  z
Extended Categories: rM  r      z  
rO  7u   
👋 Goodbye!Nu   
❌ Invalid optionu   🎉 OPERATION COMPLETEu   📁 Check images in: r   )r   r   r   r   r!  inputr   rm  ri  rl  ro  r   rH  rP  r  r   listr  r   )
r  r   example_categorieschoicer   r   rf  infor[  r)  r   r   r   main  s   
$

r~  __main__))rc  r   rB  r%  r   r   r  pathlibr   r   ior   sysrePILr   ImportErrorr   
subprocess
check_call
executabler   r   r   r   r   r   r   r   r   r   r   r   r   r   ri  rl  rm  ro  r~  r`  r   r   r   r   <module>   sD   
					3	
 #$%&'*+,-./01256789:;>?@ABEFGHIJMNOPQTUVWX[\]^abcdehijklopqrsvwxy|}~                                                !  "  #  $  %  &  ,	
.3#  J0"
U
