
    h97                         d dl Z d dlZd dlmZ d dlmZ d dlmZmZm	Z	 d dl
mZ d Zd Z G d d	      Zdd
ZddZddZddZddZy)    N)partial)BytesIO)Image
ImageChopsImageFilter)utilsc                     t        j                  |       }t        j                  |      }|r,t        ||z  dz
        dk  r||dz  k\  r||fS |dz  }|||z
  fS ||kD  rd|fS |dfS )z
    Calculate the entropy of two slices (from the start and end of an axis),
    returning a tuple containing the amount that should be added to the start
    and removed from the end of the axis.

       g{Gz?   r   )r   image_entropyabs)start_slice	end_sliceslice
differencestart_entropyend_entropy
half_slices          J/home/dcms/DCMS/lib/python3.12/site-packages/easy_thumbnails/processors.py_compare_entropyr   
   s     ''4M%%i0Ks=;6:;dB"%<aZ
5:---{"%xax    c               #   j   K   t        d      D ]!  } t        j                  | d      D ]  }|  # yw)z=
    Iterable to map a 16 bit grayscale image to 8 bits.
       N)range	itertoolsrepeat)ijs     r   _points_tabler      s<      3Z !!!S) 	AG	s   13c                   0     e Zd Z fdZd Zd Zd Z xZS )
FrameAwarec                 F    t        |dd      dkD  rt        | 	  |       S |S )Nn_framesr
   )getattrsuper__new__)clsim	__class__s     r   r&   zFrameAware.__new__)   s(    2z1%)7?3''	r   c                     || _         y N)r(   )selfr(   s     r   __init__zFrameAware.__init__.   s	    r   c                 N   g }t        | j                  j                        D ]4  }| j                  j                  |       |j	                   ||i |       6 t               }|d   j                  || j                  j                  d|dd         t        j                  |      S )Nr   Tr
   formatsave_allappend_images)
r   r(   r#   seekappendr   saver0   r   open)r,   methodargskwargs
new_framesr   write_tos          r   apply_to_frameszFrameAware.apply_to_frames1   s    
tww''( 	7AGGLLOfd5f56	7 91TWW^^d*UVUW. 	 	
 zz(##r   c                 Z    t        | j                  |      }t        | j                  |      S r+   )r$   r(   r   r<   )r,   keyr7   s      r   __getattr__zFrameAware.__getattr__<   s%    #&t++V44r   )__name__
__module____qualname__r&   r-   r<   r?   __classcell__)r)   s   @r   r!   r!   (   s    
	$5r   r!   c                    | j                   dk(  r,t        |       j                  t        t	                     d      } t        j                  |       }| j                   dv }| j                   }|s|rd}nd}|rT|rLt        | dd      s`| j                   dk7  rt        |       j                  d      } t        j                  d| j                  |      }|j                  | |        |} ng }t        | j                        D ]  }	| j                  |	       | j                   dk7  rt        |       j                  d      } t        j                  d| j                  |      }|j                  | |        |j!                  |        t#               }
|d	   j%                  |
| j&                  d
|dd        t        j(                  |
      S |dz   }| j                   |k7  rt        |       j                  |      } | S )a:  
    Convert images to the correct color space.

    A passive option (i.e. always processed) of this method is that all images
    (unless grayscale) are converted to RGB colorspace.

    This processor should be listed before :func:`scale_and_crop` so palette is
    changed before the image is resized.

    bw
        Make the thumbnail grayscale (not really just black & white).

    replace_alpha
        Replace any transparency layer with a solid color. For example,
        ``replace_alpha='#fff'`` would replace the transparency layer with
        white.

    IL)rF   LARGBis_animatedFRGBAmaskr   Tr
   Nr/   A)moder!   pointlistr   r   is_transparentr$   convertr   newsizepaster   r#   r3   r4   r   r5   r0   r6   )r(   bwreplace_alphar9   rQ   is_grayscalenew_modebaseframesr   r;   s              r   
colorspacer\   A   s   & 
ww#~ ^!!$}"7=))"-N77k)LwwHr2}e477f$#B//7Byy-@

2B
'r{{+ (AGGAJww&('^33F; 99VRWWmDDJJrJ+MM$'( #9q	RYYVTUTVZ   zz(++#~H	ww(^##H-Ir   c                    |rt        j                  |       rFt        j                  d| j                  d      }|j                  | | j                         d          n| j                  d      }|j                  d      }t        j                  d| j                  d      }t        j                  ||      j                         }|rt        |       j                  |      } | S )a$  
    Remove any unnecessary whitespace from the edges of the source image.

    This processor should be listed before :func:`scale_and_crop` so the
    whitespace is removed from the source image before it is resized.

    autocrop
        Activates the autocrop method for this image.

    rF      rK   )r   rQ   r   rS   rT   rU   splitrR   r   r   getbboxr!   crop)r(   autocropr9   no_alpharV   bgbboxs          r   rc   rc      s     #yybgg5HNN2BHHJrNN3zz#Hc" YYsBGGS)$$R,446B$$T*BIr   c           	      	   | j                   D cg c]  }t        |       c}\  }}	|D cg c]  }t        |       c}\  }
}|s|
r|s!t        |dk(  rdn|
|z  |	dk(  rdn||	z        }n t	        |dk(  rdn|
|z  |	dk(  rdn||	z        }|
st        ||z        }
n|st        |	|z        }|r4|st        ||z        }
t        |	|z        }d}|dt        |      z   dz  z  }	 t        j                  j                  }|dk  s|dkD  rJ|rHt        |       j                  t        t        ||z              t        t        |	|z              f|      } |ru| j                   \  }}	t        |t	        ||
      z
        }t        |	t	        |	|      z
        }|dk7  r0|s|r+t        |t              r(t        j                   d|      }|r|j#                         }|r"|D cg c]  }|s|dk(  rt        |      nd	 }}nd
}t        |
dz        t        |dz        }}t        ||d   z  dz        }t        |	|d   z  dz        }t        dt	        ||
z
  ||z
              t        dt	        |	|z
  ||z
              g}|j%                  t        t	        ||d   |
z                      |j%                  t        t	        |	|d   |z                      t        |t              xr t        j                   d|      }|rt'        d|j#                               r|j#                         \  }}}}|rGt	        t        |
      t        |      z  dz  |      }|r||z
  |d<   ||z
  |d<   n||d<   |||z
  z
  |d<   |r>t	        t        |      t        |      z  dz  |      }|r||z
  |d<   |	|z
  |d<   n||d<   |	||z
  z
  |d<   n|dk(  rdx}}||	} }|rot	        |t        |dz  d            }!| j)                  |d||!z   |	f      }"| j)                  ||!z
  d||	f      }#t+        |"|#|!|      \  }$}%||$z  }||%z  }||$z
  |%z
  }|ro|rot	        |t        |dz  d            }!| j)                  d||||!z   f      }"| j)                  d| |!z
  || f      }#t+        |"|#|!|      \  }$}%||$z  }| |%z  } ||$z
  |%z
  }|ro|||| f}t        |       j)                  |      } | S c c}w c c}w # t        $ r t        j                  }Y w xY wc c}w )aD	  
    Handle scaling and cropping the source image.

    Images can be scaled / cropped against a single dimension by using zero
    as the placeholder in the size. For example, ``size=(100, 0)`` will cause
    the image to be resized to 100 pixels wide, keeping the aspect ratio of
    the source image.

    crop
        Crop the source image height or width to exactly match the requested
        thumbnail size (the default is to proportionally resize the source
        image to fit within the requested thumbnail size).

        By default, the image is centered before being cropped. To crop from
        the edges, pass a comma separated string containing the ``x`` and ``y``
        percentage offsets (negative values go from the right/bottom). Some
        examples follow:

        * ``crop="0,0"`` will crop from the left and top edges.

        * ``crop="-10,-0"`` will crop from the right edge (with a 10% offset)
          and the bottom edge.

        * ``crop=",0"`` will keep the default behavior for the x axis
          (horizontally centering the image) and crop from the top edge.

        The image can also be "smart cropped" by using ``crop="smart"``. The
        image is incrementally cropped down to the requested size by removing
        slices from edges with the least entropy.

        Finally, you can use ``crop="scale"`` to simply scale the image so that
        at least one dimension fits within the size dimensions given (you may
        want to use the upscale option too).

    upscale
        Allow upscaling of the source image during scaling.

    zoom
        A percentage to zoom in on the scaled image. For example, a zoom of
        ``40`` will clip 20% off each side of the source image before
        thumbnailing.

    target
        Set the focal point as a percentage for the image if it needs to be
        cropped (defaults to ``(50, 50)``).

        For example, ``target="10,20"`` will set the focal point as 10% and 20%
        from the left and top of the image, respectively. If the image needs to
        be cropped, it will trim off the right and bottom edges until the focal
        point is centered.

        Can either be set as a two-item tuple such as ``(20, 30)`` or a comma
        separated string such as ``"20,10"``.

        A null value such as ``(20, None)`` or ``",60"`` will default to 50%.
    r   g      ?Td   g      Y@)resamplescalez(\d+)?,(\d+)?$2   )rk   rk   r   r
   z(?:(-?)(\d+))?,(?:(-?)(\d+))?$N   smart   
   )rT   floatintmaxminroundr   
ResamplingLANCZOSAttributeError	ANTIALIASr!   resize
isinstancestrrematchgroupsr4   filterrb   r   )&r(   rT   rb   upscalezoomtargetr9   vsource_xsource_ytarget_xtarget_yrj   Image__Resampling__LANCZOSdiff_xdiff_ynfocal_pointhalftarget_xhalftarget_yfocal_point_xfocal_point_ybox	edge_cropx_rightx_cropy_bottomy_cropoffsetlefttoprightbottomr   startendaddremoves&                                         r   scale_and_cropr      sX   t -/GG4q%(4Hh*./Q#a&/Hh88q=Ch&9q=Ch&9

 q=Ch&9q=Ch&9
 E)*E)*X-.HX-.HD#D	/U**5%*%5%5%=%="
 s{us{w ^""x%'()3uX5E/F+GH/ # 

 WW(XHh 778XHh 7787?&&#&"3V<#]]_FHNO1!qAvs1vB>OO$),X\):C1<M,L;q> 9C ?@M;q> 9C ?@MAs8h.0LMNAs8h.0LMNC JJs3xQ():;<=JJs3xQ():;<="4- "((143I VD)*:*:*<=4=4D4D4F16 XV!<!CVLF!'&A!)F!2A!'A!)Vf_!=A XV!<!CVLF!'&A!)F!2A!'A!)Vf_!=As ((vFaK(<=EGGT1dUlH$EFE''55=!UH"EFC"25#uf"MKCCKDVOE#c\F2F  FaK(<=EGGQXsU{$CDE''1funh"GHC"25#uf"MKC3JCf$F#c\F2F  S%0B$$S)BIc 5/<  5%*__"50 Ps"   S
S"S S4S10S1c                     |r(t        |       j                  t        j                        } |r(t        |       j                  t        j                        } | S )z
    Pass the source image through post-processing filters.

    sharpen
        Sharpen the thumbnail image (using the PIL sharpen filter)

    detail
        Add detail to the image, like a mild *sharpen* (using the PIL
        ``detail`` filter).

    )r!   r   r   DETAILSHARPEN)r(   detailsharpenr9   s       r   filtersr   J  sC     ^"";#5#56^"";#6#67Ir   c                    |s| S |d   r|d   s| S | j                   \  }}||d   k\  r
||d   k\  r| S t        | fd|i|} t        j                  d||      }|j                  | j                  k7  r|j                  | j                        }|d   |z
  dz  |d   |z
  dz  f}t        | dd      s|j                  | |       |S g }t        | j                        D ]F  }	| j                  |	       |j                         }
|
j                  | |       |j                  |
       H t               }|d   j                  || j                  d|dd	 
       t        j                   |      S )z
    Add borders of a certain color to make the resized image fit exactly within
    the dimensions given.

    background
        Background color to use
    r   r
   rW   rH   r   rI   FTNr/   )rT   r\   r   rS   rN   rR   r$   rU   r   r#   r3   copyr4   r   r5   r0   r6   )r(   rT   
backgroundr9   xynew_imr   r[   r   copied_new_imr;   s               r   r   r   ]  sc    	7$q'	77DAqDG|T!W 		B	;j	;F	;BYYudJ/F{{bgg(1gka$q'A+!!33F2}e,R r{{# 	)AGGAJ"KKMMF+MM-(		)
 9q	RYYVABZ 	 	
 zz(##r   )FF)F)FFNNr+   )r   r|   	functoolsr   ior   PILr   r   r   easy_thumbnailsr   r   r   r!   r\   rc   r   r   r    r   r   <module>r      sJ     	   . . !*5 52;|:k\&'$r   