o
    rqi@F                     @   s|   d dl Z d dlZd dlmZmZ d dlmZ d dlZd dlm	Z	 d dl
mZmZmZ d dlmZ e ZdZG dd	 d	ZdS )
    N)ListOptional)urlparse)tqdm)MODELSCOPE_URL_SCHEMEencode_image_to_base64get_endpoint)
get_loggerzihttps://modelscope.cn/models/modelscope/modelscope_aigc_default_logo/resolve/master/aigc_default_logo.pngc                   @   s  e Zd ZdZh dZh dZh dZ							d/d	ed
edededee dee dee	e  dee dee	e  dee	e  fddZ
dd Zdd Zdd Zdd Zd0dedee fdd Zdd!ddd"d#ee d$ed%ee d&ee d'df
d(d)Zd'efd*d+Zed,efd-d.ZdS )1	AigcModela[  
    Helper class to encapsulate AIGC-specific model creation parameters.

    This class can be initialized directly with parameters, or loaded from a
    JSON configuration file using the `from_json_file` classmethod.

    Example of direct initialization:
        >>> aigc_model = AigcModel(
        ...     aigc_type='Checkpoint',
        ...     base_model_type='SD_XL',
        ...     model_path='/path/to/your/model.safetensors'
        ...     base_model_id='AI-ModelScope/FLUX.1-dev'
        ... )

    Example of loading from a JSON file:
        `config.json`:
        {
            "model_path": "/path/to/your/model.safetensors",
            "aigc_type": "Checkpoint",
            "base_model_type": "SD_XL",
            "base_model_id": "AI-ModelScope/FLUX.1-dev"
        }

        >>> aigc_model = AigcModel.from_json_file('config.json')
    >   ZLoRAZ
CheckpointZVAE>   ZSD_2_1ZSD_XLZWAN_VIDEO_2_2_TI2V_5_BZSD_1_5UNKNOWNZWAN_VIDEO_2_1_I2V_14_BZWAN_VIDEO_2_1_14_BZWAN_VIDEO_2_2_T2V_A_14_BZSD_2ZWAN_VIDEO_2_2_I2V_A_14_BZFLUX_1ZQWEN_IMAGE_20_BZWAN_VIDEO_2_1_T2V_14_BZWAN_VIDEO_2_1_T2V_1_3_BZWAN_VIDEO_2_1_FLF2V_14_BZSD_3>   zcharacter-strongzarchitectural-designZ	commodityzclassic-painting-styleZfoodzother-styleszautomobile-trafficZclothingzflat-abstractionzsci-fi-mechaZsceneryzmain-strongZplantze-commerce-designztoy-figurinesz
cg-fantasywomanmanzillustration-designzart-style-strongZ3dzother-functionszpicture-controlconstruction	dimensionZphotographyZanimalzhand-drawn-styleZartwarezcharacter-enhancementZlogo v1.0this is an aigc modelN	aigc_typebase_model_type
model_pathbase_model_idtagdescriptioncover_imagespath_in_repotrigger_wordsofficial_tagsc                 C   s6  || _ || _|| _|| _|| _|dursg }|D ]W}t|tri|dsc|dsc|dsczt|}|	| t
dtj| W q ttfyb } zt
d|| |	| W Y d}~qd}~ww |	| q|	| q|| _ntg| _|| _|| _|	| _|   |   |
r|
| _|   nd| _|   dS )a  
        Initializes the AigcModel helper.

        Args:
            model_path (str): The path of checkpoint/LoRA weight file or folder.
            aigc_type (str): AIGC model type. Recommended: 'Checkpoint', 'LoRA', 'VAE'.
            base_model_type (str): Vision foundation model type. Recommended values are in BASE_MODEL_TYPES.
            tag (str, optional): Tag for the AIGC model. Defaults to 'v1.0'.
            description (str, optional): Model description. Defaults to 'this is an aigc model'.
            cover_images (List[str], optional): List of cover image URLs.
            base_model_id (str, optional): Base model name. e.g., 'AI-ModelScope/FLUX.1-dev'.
            path_in_repo (str, optional): Path in the repository.
            trigger_words (List[str], optional): Trigger words for the AIGC Lora model.
            official_tags (List[str], optional): Official tags for the AIGC model. Defaults to None.
        Nzhttp://zhttps://zdata:z#Converted local image to base64: %sz2Failed to process local image %s: %s. Using as-is.)r   r   r   r   r   
isinstancestr
startswithr   appendloggerinfoospathbasenameFileNotFoundError
ValueErrorwarningr   DEFAULT_AIGC_COVER_IMAGEr   r   r   _validate_aigc_type_validate_base_model_typer   _validate_official_tags_process_model_path)selfr   r   r   r   r   r   r   r   r   r   Zprocessed_cover_imagesimgZprocessed_imge r1   `/home/app/PaddleOCR-VL/.venv_paddleocr/lib/python3.10/site-packages/modelscope/hub/utils/aigc.py__init__H   sT   




zAigcModel.__init__c                 C   >   | j | jvrdt| j}td| j  d| d dS dS )z?Validate aigc_type and provide a warning for unsupported types., zUnsupported aigc_type: "z". Recommended values: z1. Custom values are allowed but may cause issues.N)r   
AIGC_TYPESjoinsortedr!   r(   r.   Zsupported_typesr1   r1   r2   r*      s   zAigcModel._validate_aigc_typec                 C   r4   )zCValidate base_model_type and provide warning for unsupported types.r5   zYour base_model_type: "z," may not be supported. Recommended values: z2. Custom values are allowed but may cause issues. N)r   BASE_MODEL_TYPESr7   r8   r!   r(   r9   r1   r1   r2   r+      s   
z#AigcModel._validate_base_model_typec                    sX    fdd j D }|r*d j}ddd |D }td| d| d d	S d	S )
z@Validate official tags and provide warning for unsupported tags.c                    s   h | ]	}| j vr|qS r1   )OFFICIAL_TAGS.0r   r.   r1   r2   	<setcomp>   s    z4AigcModel._validate_official_tags.<locals>.<setcomp>r5   c                 s   s    | ]	}d | d V  qdS )"Nr1   r<   r1   r1   r2   	<genexpr>   s    z4AigcModel._validate_official_tags.<locals>.<genexpr>zYour tag(s): z+ may not be supported. Recommended values: z. N)r   r7   r;   r!   r(   )r.   Zinvalid_tagssupported_tagsZinvalid_tags_strr1   r>   r2   r,      s   
z!AigcModel._validate_official_tagsc                    sL  ddl m} tj j _tj jstd j tj jr2 j}t	
dtj| ntj jrt j}t|dkrNtd j d fdd|D }h d	}|rmd
d |D }||rmtdg d}d}|D ]M}ttj jd| }	|	r|	d }t	
d| dtj| t|	dkrt	d| dtj| t	
d| ddd |	dd D   nqu|s fddt jD }
|
rtj j|
d }t	dtj| t	
d|
 ntd j dntd j |r$t	
d| ||}tj| _|d  _|d   _| _dS dS )!z0Process model_path to extract weight informationr   )get_file_hashzModel path does not exist: zUsing file: %szDirectory is empty: zW. Please place at least one model file at the top level (e.g., .safetensors/.pth/.bin).c                    (   g | ]}t jt j j|r|qS r1   r#   r$   isfiler7   r   r=   namer>   r1   r2   
<listcomp>       z1AigcModel._process_model_path.<locals>.<listcomp>>   z	readme.mdzconfiguration.jsonz.gitattributesc                 S   s   h | ]}|  qS r1   )lowerrG   r1   r1   r2   r?      s    z0AigcModel._process_model_path.<locals>.<setcomp>zTop-level directory contains only [.gitattributes, configuration.json, README.md]. Please place additional model files at the top level (e.g., .safetensors/.pth/.bin).)z.safetensorsz.pthz.binN*zFound z	 file: %s   z	Multiple z$ files found, using: %s for metadatazOther z
 files: %sc                 S   s   g | ]}t j|qS r1   )r#   r$   r%   r=   fr1   r1   r2   rI      s    c                    rD   r1   rE   rN   r>   r1   r2   rI      rJ   z:No safetensors/pth/bin files found, using: %s for metadatazAvailable files: %szNo files found in directory: zI. AIGC models require at least one model file (.safetensors recommended).z(Model path must be a file or directory: z!Computing hash and size for %s...Z	file_hash	file_size)Zmodelscope.utils.file_utilsrC   r#   r$   
expanduserr   existsr'   rF   r!   r"   r%   isdirlistdirlenissubsetglobr7   r(   weight_filenameweight_sha256weight_sizetarget_file)r.   rC   r[   Ztop_entriesZ	top_filesZplaceholder_names
normalizedZfile_extensionsextfiles	all_files	hash_infor1   r>   r2   r-      s   











zAigcModel._process_model_pathmodel_idtokenc              
   C   s   t d| zNtj| jr"t d| j |j|| j| j|dd n*tj| jrLt d| j	 |j
| j	| jr?| jd | j n| j||d| j dd	 t d
| W dS  tyr } zt d| t d W Y d}~dS d}~ww )z!Upload model files to repository.zUploading model to %s...zUploading directory: %sz"Upload model folder for AIGC model)repo_idZfolder_pathr   rb   commit_messagezUploading file: %s/zUpload z for AIGC model)Zpath_or_fileobjr   rc   rb   rd   z!Successfully uploaded model to %sTz#Warning: Failed to upload model: %sz9You may need to upload the model manually after creation.NF)r!   r"   r#   r$   rS   r   Zupload_folderr   rF   r[   Zupload_filerX   	Exceptionr(   )r.   apira   rb   r0   r1   r1   r2   upload_to_repo  s@   	zAigcModel.upload_to_repoi,  )cookiestimeoutheadersendpointri   rj   rk   rl   returnc             	   C   s  |pt  }t| jd}|dst d| n	t d|d }| d}t| ddp2| j}t	j
t	j
|}t	j
|sJtd	| |rPt|nd}|du rZtd
|dd|d  i t	j
|}		ddtfdd}
t|	ddddd)}t|d}tj|||
|||d}W d   n1 sw   Y  W d   n1 sw   Y  z| }W n tjjy   |  Y dS w t|tr|ddu r|dd}td| dS dS )a  Pre-upload aigc model weights to the LFS server.

        Server may require the sha256 of weights to be registered before creation.
        This method streams the weight file so the sha gets registered.

        Args:
            cookies: Optional requests-style cookies (CookieJar/dict). If provided, preferred.
            timeout: Request timeout seconds.
            headers: Optional headers.
        zwww.prezlfs.zpre-lfs.zpre.z/api/v1/models/aigc/weightsr[   Nz Pre-upload expects a file, got: z)Token does not exist, please login first.Cookiezm_session_id=Zm_session_id   
chunk_sizec                 s   s,    	 |  |}|sd S |t| |V  qN)readupdaterU   )Zfile_objectpbarrq   Zckr1   r1   r2   read_in_chunksS  s   
z3AigcModel.preupload_weights.<locals>.read_in_chunksBTz[Pre-uploading] )totalunitZ
unit_scaleZdynamic_ncolsZdescrb)rk   datarj   ZSuccessFMessagezunknown errorzPre-upload failed: )rp   )r   r   striphostnamelstripr   r   getattrr   r#   r$   abspathrQ   rF   r'   dictrt   getsizeintr   openrequestsputjson
exceptionsJSONDecodeErrorraise_for_statusr   getRuntimeError)r.   ri   rj   rk   rl   Zendpoint_hostbase_urlurl	file_pathrP   rv   ru   rO   rrespmsgr1   r1   r2   preupload_weights-  s^   



zAigcModel.preupload_weightsc                 C   s6   | j | j| j| j| j| j| j| j| j| j	| j
| jdS )zDConverts the AIGC parameters to a dictionary suitable for API calls.r   r   r   r   r   r   r   rX   rY   rZ   r   r   r   r>   r1   r1   r2   to_dictt  s   zAigcModel.to_dict	json_pathc                 C   s   ddl }tj|}tj|std| t|ddd}||}W d   n1 s.w   Y  g d}|D ]}||vrGtd| d	q9| d
i |S )z
        Creates an AigcModel instance from a JSON configuration file.

        Args:
            json_path (str): The path to the JSON configuration file.

        Returns:
            AigcModel: An instance of the AigcModel.
        r   NzJSON config file not found at: r   zutf-8)encoding)r   r   r   r   z(Missing required field in JSON config: ''r1   )	r   r#   r$   rQ   rR   r&   r   loadr'   )clsr   r   rO   configZrequired_fieldsfieldr1   r1   r2   from_json_file  s"   
zAigcModel.from_json_file)r   r   r   Nr   NNrr   )__name__
__module____qualname____doc__r6   r:   r;   r   r   r   r3   r*   r+   r,   r-   rh   objectr   r   r   r   classmethodr   r1   r1   r1   r2   r
      sp    	

	


L	Z#
Gr
   )rW   r#   typingr   r   urllib.parser   r   Z	tqdm.autor   Zmodelscope.hub.utils.utilsr   r   r   Zmodelscope.utils.loggerr	   r!   r)   r
   r1   r1   r1   r2   <module>   s   