
    ~R:i                     v    d dl mZ d dlmZ d dlmZ d dlmZ d dlm	Z	  ee
      Zdededefd	Zd
 ZdefdZy)    )Pathgcd)PSDImage)setup_logger)KEYWORDSwidthheightreturnc                 J    | dk(  s|dk(  ryt        | |      }| |z   d||z   S )z Return simplified ratio. r   0:0:r   )r	   r
   gs      E/var/www/html/story-book/Story-Book-python-api/app/utils/psd_ratio.pysimplify_ratior   
   s7    zVq[E6Aqj\6Q;-((    c                 l   t        | dd      }|sy	 t        |t        t        f      rt	        t
        |      \  }}}}nWt        |j                        t        |j                        t        |j                        t        |j                        f\  }}}}||kD  r||kD  r||||fS dS # t        $ r Y yw xY w)z<Same bbox extraction logic you used in generate_final_image.bboxN)getattr
isinstancetuplelistmapintx1y1x2y2	Exception)layerr   r   r   r   r   s         r   
_safe_bboxr!      s    5&$'DdUDM* d^NBB \3tww<TWWs477|SNBB$&GRBBBdB s   BB' %B' '	B32B3psd_pathc                    	 t        j                  |       }t        |dd      }t        |dd      }t        ||      }g }|j                         D ]  }	 t        |d      r|j                  st        |dd      xs dj                         t        |d	d      }|d
k(  st        fdt        D              r t        |      }|r|j                  ||f        |s|S t        |      dkD  r|S |d   \  }	}|\  }
}}}||
z
  }||z
  }t        ||      S # t        $ r t        j	                  d       Y yw xY w# t        $ r Y w xY w)z
    Rule:
    - If exactly 1 design layer -> return that layer's bbox ratio
    - If 2+ design layers -> return PSD canvas ratio
    zError opening PSDr   r	   r   r
   visiblename kindsmartobjectc              3   &   K   | ]  }|v  
 y w)N ).0kr%   s     r   	<genexpr>z$extract_psd_ratio.<locals>.<genexpr>>   s     +Hx!AIxs      )r   openr   logger	exceptionr   r   descendantshasattrr$   loweranyr   r!   appendlen)r"   psdpsd_wpsd_h	psd_ratiodesign_layersr    r'   r   _r   r   r   r   whr%   s                   @r   extract_psd_ratior@   "   s`   mmH% C!$EC1%Eue,I M"	ui(E62.4";;=D5&"-D}$+Hx+H(H!%(!((%7 #  
=A AGAtNBB
RA
RA!QS  ,-0  		s*   D D5-A)D5D21D25	E EN)pathlibr   mathr   	psd_toolsr   app.core.loggingr   app.core.constantsr   __name__r0   r   strr   r!   r@   r*   r   r   <module>rH      sI       ) '	h	)# )s )s ) 2  2 r   