a
    Ad<                     @   s*  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
mZmZmZ d dlmZ dZeeZedZedZee Zi Zg ZG dd	 d	Zd
d Zdd Zdd Zdd Zd(ddZdd Z dd Z!edddZ"dd Z#dd Z$dd  Z%e&d!d"d#Z'g Z(d$d% Z)d&d' Z*dS ))    N)	data_path)shared
ui_tempdirscript_callbacks
processing)Imagez/\s*([\w ]+):\s*("(?:\\.|[^\\"])+"|[^,]*)(?:,|$)z^(\d+)x(\d+)$z\(([0-9a-f]+)\)$c                   @   s   e Zd ZdddZdS )ParamBindingNc                 C   s2   || _ || _|| _|| _|| _|| _|p*g | _d S N)paste_buttontabnamesource_text_componentsource_image_componentsource_tabnameoverride_settings_componentpaste_field_names)selfr
   r   r   r   r   r   r    r   O/var/www/html/stable-diffusion-webui/modules/generation_parameters_copypaste.py__init__   s    zParamBinding.__init__)NNNNN)__name__
__module____qualname__r   r   r   r   r   r      s   r   c                   C   s   t   t  d S r	   )paste_fieldsclearregistered_param_bindingsr   r   r   r   reset!   s    r   c                 C   s6   dt | vr(dt | vr(dt | vr(| S tj| ddS )N,
:F)ensure_ascii)strjsondumpstextr   r   r   quote&   s    $r%   c                 C   sP   t | dks$| d dks$| d dkr(| S zt| W S  tyJ   |  Y S 0 d S )Nr   ")lenr!   loads	Exceptionr#   r   r   r   unquote-   s    $r+   c                 C   s   | d u rd S t | tkrD| rDt | d tkrD| d ddrD| d } t | tkr| ddr| d }ttj|}|s~J d|ddd }t	
|S t | tkrt| dkrd S | d } | dr| tdd  } t| d	} t	
t| }|S )
Nr   is_fileFnamez8trying to open image file outside of allowed directories?   zdata:image/png;base64,zutf-8)typelistdictgetr   Zcheck_tmp_filer   demorsplitr   openr(   
startswithbase64decodebytesencodeioBytesIO)ZfiledatafilenameZis_in_right_dirimager   r   r   image_from_url_text7   s&    0

r?   c                 C   s>   |||dt | < dd l}| dkr*||j_n| dkr:||j_d S )N)init_imgfieldsr   r   txt2imgimg2img)r   Z
modules.uiuiZtxt2img_paste_fieldsZimg2img_paste_fields)r   r@   rA   r   modulesr   r   r   add_paste_fieldsT   s    
rF   c                 C   s0   i }| D ]"}t jd| | dd||< q|S )NzSend to Z_tab)elem_id)grButton)Z	tabs_listbuttonstabr   r   r   create_buttons_   s     rL   c              	   C   sT   |   D ]F\}}t|tjjr"|nd}t|tr4|nd}tt|||||d qdS )z[old function for backwards compatibility; do not use this, use register_paste_params_buttonN)r
   r   r   r   r   )items
isinstancerH   
components	Componentr    register_paste_params_buttonr   )rJ   Z
send_imageZsend_generate_infor   buttonr   r   r   r   r   bind_buttonsf   s    rS   bindingc                 C   s   t |  d S r	   )r   appendrT   r   r   r   rQ   o   s    rQ   c                     s  t D ]} t| j d }t| j d }| jp8t| j d }tt|rPdd |D ng d }tt|rpdd |D ng d }| jr|rt| jtj	r|rt
nt}d}n|rt
ndd	 }d }| jj||| jg|r|||gn|gd
d | jd ur|d urt| j|| j|| j | jd ur|d urg dtjjr:dgng  | j  | jjdd	  fddt| j d D  fdd|D d
d | jjd d| j d d d
d qd S )Nr@   rA   r   c                 S   s   g | ]\}}|d kr|qS )Size-1r   .0fieldr-   r   r   r   
<listcomp>z       z0connect_paste_params_buttons.<locals>.<listcomp>c                 S   s   g | ]\}}|d kr|qS )Size-2r   rX   r   r   r   r[   {   r\   Zextract_image_from_galleryc                 S   s   | S r	   r   xr   r   r   <lambda>   r\   z.connect_paste_params_buttons.<locals>.<lambda>Ffn_jsinputsoutputsshow_progress)PromptNegative promptStepszFace restorationSeedc                  W   s   | S r	   r   r^   r   r   r   r`      r\   c                    s   g | ]\}}| v r|qS r   r   rX   r   r   r   r[      r\   c                    s   g | ]\}}| v r|qS r   r   rX   rk   r   r   r[      r\   rb   rd   re   rf   Z
switch_to_)r   r   r   r   nextiterr   rN   rH   Gallerysend_image_and_dimensionsr?   r
   clickr   connect_paster   r   opts	send_seedr   )rU   Zdestination_image_componentrA   r   Zdestination_width_componentZdestination_height_componentfuncZjsfuncr   rk   r   connect_paste_params_buttonss   sH    
  
"
rv   c                 C   sV   t | tjr| }nt| }tjjr<t |tjr<|j}|j}nt	 }t	 }|||fS r	   )
rN   r   r?   r   rs   	send_sizewidthheightrH   update)r_   imgwhr   r   r   rp      s    rp   c                 C   s   |  dd}|  dd}tjjr\t|  dd}t|  dd}|r\|r\|| d< || d< dS |du sl|du rpdS t|t| }}t|  dd	}t|  dd	}|dks|dkrt||\}}|| d< || d< || d< || d< dS )
zifor infotexts that specify old First pass size parameter, convert it into
    width, height, and hr scalezFirst pass size-1NzFirst pass size-2Hires resize-1r   Hires resize-2rW   r]   i   )r3   r   rs   use_old_hires_fix_width_heightintr   #old_hires_fix_first_pass_dimensions)resZfirstpass_widthZfirstpass_heightZhires_widthZhires_heightrx   ry   r   r   r   restore_old_hires_fix_params   s(    r   r^   c              
   C   s  i }d}d}d}|   d^ }}tt|dk rD|| d}|D ]`}|  }|drrd}|dd   }|r||dkrdnd| 7 }qH||dkrdnd| 7 }qHtjj	d	krtj
||\}}}tjj	d
kr||d< ntjj	dkr|r||d< ||d< ||d< t|D ]\}	}
zn|
d dkr@|
d dkr@t|
}
t|
}|dur~|d||	 d< |d||	 d< n|
||	< W n* ty   td|	 d|
 d Y n0 qd|vrd|d< |dd}|dur|d  d| d|dd d7  < d |vr d|d < d|d!< d"|vr2d#|d"< d$|vrDd%|d$< d&|vrVd|d&< d'|vrhd|d'< t| d(|vrd)|d(< d*|vrd+|d*< d,|vrd|d,< d-|vrd|d-< d.|vrd|d.< d/|vrd0|d/< d1|vrd0|d1< |S )2ag  parses generation parameters string, the one you see in text field under the picture in UI:
```
girl with an artist's beret, determined, blue eyes, desert scene, computer monitors, heavy makeup, by Alphonse Mucha and Charlie Bowater, ((eyeshadow)), (coquettish), detailed, intricate
Negative prompt: ugly, fat, obese, chubby, (((deformed))), [blurry], bad anatomy, disfigured, poorly drawn face, mutation, mutated, (extra_limb), (ugly), (poorly drawn hands), messy drawing
Steps: 20, Sampler: Euler a, CFG scale: 7, Seed: 965400086, Size: 512x512, Model hash: 45dee52b
```

    returns a dict with field values
     Fr      zNegative prompt:T   NIgnoreApplyzStyles arrayzApply if anyrg   rh   r   r&   r'   r/   z-1   z-2zError parsing ": z	Clip skip1ZHypernetz
<hypernet:r   zHypernet strengthz1.0>r~   r   zHires samplerzUse same samplerzHires checkpointzUse same checkpointzHires promptzHires negative promptRNGGPUzSchedule type	AutomaticzSchedule max sigmazSchedule min sigmazSchedule rhozVAE EncoderFullzVAE Decoder)stripsplitr(   re_paramfindallrV   r7   r   rs   infotext_stylesprompt_stylesextract_styles_from_promptr+   re_imagesizematchgroupr*   printr3   r   )r_   r   promptnegative_promptZdone_with_promptlineslastlinelineZfound_styleskvmhypernetr   r   r   parse_generation_parameters   s    




 

&











r   c           
      C   s   i }i }| D ]"}|j ddd\}}| ||< qdd tjj D }|t D ]0\}}||d}	|	du rlqNtj||	||< qN|S )a'  creates processing's override_settings parameters from gradio's multiselect

    Example input:
        ['Clip skip: 2', 'Model hash: e6e99610c4', 'ENSD: 31337']

    Example output:
        {'CLIP_stop_at_last_layers': 2, 'sd_model_checkpoint': 'e6e99610c4', 'eta_noise_seed_delta': 31337}
    r   r/   )maxsplitc                 S   s    g | ]\}}|j r|j |fqS r   infotextrY   r   infor   r   r   r[   `  r\   z1create_override_settings_dict.<locals>.<listcomp>N)	r   r   r   rs   data_labelsrM    infotext_to_setting_name_mappingr3   
cast_value)
Z
text_pairsr   paramspairr   r   mapping
param_namesetting_namevaluer   r   r   create_override_settings_dictN  s    
r   c                    sx   fdd}|d ur<dd D   fdd}||fg | j ||gdd D d	d
 | j d d| g g d	d d S )Nc           
   	      s4  | s\t jjs\tjtd}tj|r\t|ddd}|	 } W d    n1 sR0    Y  t
| }t| | g } D ]\}}t|r||}n||d }|d u r|t  qxt|tr|| qxz>t|j}|tkr|dkrd}	n||}	|tj|	d W qx ty,   |t  Y qx0 qx|S )Nz
params.txtrutf8)encodingFalseF)r   )r   cmd_optshide_ui_dir_configospathjoinr   existsr6   readr   r   infotext_pasted_callbackcallabler3   rV   rH   rz   rN   type_of_gr_updater0   r   boolr*   )
r   r=   filer   r   outputkeyr   Zvaltypeval)r   r   r   
paste_funcm  s2    &


z!connect_paste.<locals>.paste_funcc                 S   s   i | ]\}}|d qS )r/   r   )rY   _r   r   r   r   
<dictcomp>  r\   z!connect_paste.<locals>.<dictcomp>c                    s   i }dd t jj D }|t D ]h\}}| v r4q"| |d }|d u rJq"|dkr\t jjr\q"t j||}tt j|d }||krq"|||< q"dd | D }t	j
j||t|dS )Nc                 S   s    g | ]\}}|j r|j |fqS r   r   r   r   r   r   r[     r\   z9connect_paste.<locals>.paste_settings.<locals>.<listcomp>sd_model_checkpointc                 S   s   g | ]\}}| d | qS )r   r   )rY   r   r   r   r   r   r[     r\   )r   choicesvisible)r   rs   r   rM   r   r3   disable_weights_auto_swapr   getattrrH   Dropdownrz   r   )r   valsr   r   r   r   current_valueZ
vals_pairs)already_handled_fieldsr   r   paste_settings  s"    
z%connect_paste.<locals>.paste_settingsc                 S   s   g | ]}|d  qS )r   r   )rY   r_   r   r   r   r[     r\   z!connect_paste.<locals>.<listcomp>Frl   Zrecalculate_prompts_ra   )rq   )rR   r   Z
input_compr   r   r   r   r   )r   r   r   rr   l  s$    $rr   )N)+r8   r;   r!   r   regradiorH   modules.pathsr   rE   r   r   r   r   PILr   Zre_param_codecompiler   r   Zre_hypernet_hashr0   rz   r   r   r   r   r   r%   r+   r?   rF   rL   rS   rQ   rv   rp   r   r    r   r   r   rr   r   r   r   r   <module>   s>   




	/ m