Ë
    5¾ªj�  ã                   ó‚   — d Z ddlmZmZmZ ddlZddlmZ ddl	m
Z
 ddlmZmZmZmZmZmZmZ ddlmZ  G d„ d	e«      Zy)
z«Embeddings integration utilities for MySQL Connector/Python.

Provides MyEmbeddings class to generate embeddings via MySQL HeatWave
using ML_EMBED_TABLE and ML_EMBED_ROW.
é    )ÚDictÚListÚOptionalN)Ú
Embeddings)ÚPrivateAttr)Úatomic_transactionÚexecute_sqlÚformat_value_sqlÚsource_schemaÚsql_table_from_dfÚsql_table_to_dfÚtemporary_sql_tables)ÚMySQLConnectionAbstractc                   óˆ   ‡ — e Zd ZU dZ e«       Zeed<   	 ddedee	   fˆ fd„Z
dee   deee      fd„Zd	edee   fd
„Zˆ xZS )ÚMyEmbeddingsa€  
    Embedding generator class that uses a MySQL database to compute embeddings for input text.

    This class batches input text into temporary SQL tables, invokes MySQL's ML_EMBED_TABLE
    to generate embeddings, and retrieves the results as lists of floats.

    Attributes:
        _db_connection (MySQLConnectionAbstract): MySQL connection used for all database operations.
        schema_name (str): Name of the database schema to use.
        options_placeholder (str): SQL-ready placeholder string for ML_EMBED_TABLE options.
        options_params (dict): Dictionary of concrete option values to be passed as SQL parameters.
    Ú_db_connectionÚdb_connectionÚoptionsc                 óŒ   •— t         ‰| �  «        || _        t        |«      | _        |xs i }t        |«      \  | _        | _        y)a“  
        Initialize MyEmbeddings with a database connection and optional embedding parameters.

        References:
            https://dev.mysql.com/doc/heatwave/en/mys-hwgenai-ml-embed-row.html
                A full list of supported options can be found under "options"

        NOTE: The supported "options" are the intersection of the options provided in
            https://dev.mysql.com/doc/heatwave/en/mys-hwgenai-ml-embed-row.html
            https://dev.mysql.com/doc/heatwave/en/mys-hwgenai-ml-embed-table.html

        Args:
            db_connection: Active MySQL connector database connection.
            options: Optional dictionary of options for embedding operations.

        Raises:
            ValueError: If the schema name is not valid
            DatabaseError:
                If a database connection issue occurs.
                If an operational error occurs during execution.
        N)ÚsuperÚ__init__r   r   Úschema_namer
   Úoptions_placeholderÚoptions_params)Úselfr   r   Ú	__class__s      €úW/var/www/html/serviGia/entorno/lib/python3.12/site-packages/mysql/ai/genai/embedding.pyr   zMyEmbeddings.__init__F   sC   ø€ ô0 	‰ÑÔØ+ˆÔÜ(¨Ó7ˆÔØ’-˜RˆÜ8HÈÓ8QÑ5ˆÔ  $Õ"5ó    ÚtextsÚreturnc           	      óú  — |sg S t        j                  t        t        |«      «      |dœ«      }t	        | j
                  «      5 }t        | j
                  «      5 }t        || j                  |«      \  }}|j                  | j                  |f«       d|› d|› d| j                  › d�}t        ||| j                  ¬«       t        || j                  |«      }|d   j                  «       j                  «       st        d„ |d   D «       «      rt!        d	«      ‚|d   j#                  «       }	|	D �
cg c]  }
t%        |
«      ‘Œ }	}
|	cd
d
d
«       cd
d
d
«       S c c}
w # 1 sw Y   nxY wd
d
d
«       y
# 1 sw Y   y
xY w)a†  
        Generate embeddings for a list of input texts using the MySQL ML embedding procedure.

        References:
            https://dev.mysql.com/doc/heatwave/en/mys-hwgenai-ml-embed-table.html

        Args:
            texts: List of input strings to embed.

        Returns:
            List of lists of floats, with each inner list containing the embedding for a text.

        Raises:
            DatabaseError:
                If provided options are invalid or unsupported.
                If a database connection issue occurs.
                If an operational error occurs during execution.
            ValueError:
                If one or more text entries were unable to be embedded.

        Implementation notes:
            - Creates a temporary table to pass input text to the MySQL embedding service.
            - Adds a primary key to ensure results preserve input order.
            - Calls ML_EMBED_TABLE and fetches the resulting embeddings.
            - Deletes the temporary table after use to avoid polluting the database.
            - Embedding vectors are extracted from the "embeddings" column of the result table.
        )ÚidÚtextzCALL sys.ML_EMBED_TABLE('z	.text', 'z.embeddings', ú)©ÚparamsÚ
embeddingsc              3   ó$   K  — | ]  }|d u –— Œ
 y ­w©N© )Ú.0Úes     r   ú	<genexpr>z/MyEmbeddings.embed_documents.<locals>.<genexpr>›   s   è ø€ ò AØ��T”	ñAùs   ‚z:Failure to generate embeddings for one or more text entry.N)ÚpdÚ	DataFrameÚrangeÚlenr   r   r   r   r   Úappendr   r	   r   r   ÚisnullÚanyÚ
ValueErrorÚtolistÚlist)r   r   ÚdfÚcursorÚtemporary_tablesÚqualified_table_nameÚ
table_nameÚembed_queryÚdf_embeddingsr'   r,   s              r   Úembed_documentszMyEmbeddings.embed_documentsd   s�  € ñ8 ØˆIä�\‰\¤¤s¨5£zÓ!2¸EÑBÓCˆô ˜t×2Ñ2Ó3ð!	Ø7=Ü  ×!4Ñ!4Ó5ð!	à9Iä/@Ø˜×(Ñ(¨"ó0Ñ,Ð  *ð ×#Ñ# T×%5Ñ%5°zÐ$BÔCðØ(Ð)ð *Ø(Ð)¨Ø×+Ñ+Ð,Øð	ð ô ˜ °D×4GÑ4GÕHô ,¨F°D×4DÑ4DÀjÓQˆMà˜\Ñ*×1Ñ1Ó3×7Ñ7Ô9¼Sñ AØ#0°Ñ#>ôAô >ô !ØPóð ð
 ' |Ñ4×;Ñ;Ó=ˆJØ+5Ö6 aœ$˜q�'Ð6ˆJÐ6à÷C!	÷ !	ò !	ùò> 7÷?!	ð !	ú÷ !	÷ !	ñ !	ús7   ÁE1ÁCEÄ/EÅEÅ	E1ÅEÅE%	Å!E1Å1E:r#   c                 óä   — t        | j                  «      5 }t        |d| j                  › d�|g| j                  ¢­¬«       t        |j                  «       d   «      cddd«       S # 1 sw Y   yxY w)a…  
        Generate an embedding for a single text string.

        References:
            https://dev.mysql.com/doc/heatwave/en/mys-hwgenai-ml-embed-row.html

        Args:
            text: The input string to embed.

        Returns:
            List of floats representing the embedding vector.

        Raises:
            DatabaseError:
                If provided options are invalid or unsupported.
                If a database connection issue occurs.
                If an operational error occurs during execution.

        Example:
            >>> MyEmbeddings(db_conn).embed_query("Hello world")
            [0.1, 0.2, ...]
        zSELECT sys.ML_EMBED_ROW("%s", r$   r%   r   N)r   r   r	   r   r   r7   Úfetchone)r   r#   r9   s      r   r=   zMyEmbeddings.embed_query¨   sn   € ô.   × 3Ñ 3Ó4ð 	.¸ÜØØ0°×1IÑ1IÐ0JÈ!ÐLØÐ3˜t×2Ñ2Ñ3õô
 ˜Ÿ™Ó)¨!Ñ,Ó-÷	.÷ 	.ò 	.ús   –AA&Á&A/r)   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   r   Ú__annotations__r   r   r   r   ÚstrÚfloatr?   r=   Ú__classcell__)r   s   @r   r   r   6   su   ø… ññ /:«m€NÐ+Ó;ð QUñRØ4ðRØ?GÈ¹~õRð<B T¨#¡Yð B°4¸¸U¹Ñ3Dó BðH. ð .¨¨U©÷ .r   r   )rE   Útypingr   r   r   Úpandasr.   Úlangchain_core.embeddingsr   Úpydanticr   Úmysql.ai.utilsr   r	   r
   r   r   r   r   Úmysql.connector.abstractsr   r   r*   r   r   ú<module>rP      s=   ðñ:÷ (Ñ 'ã å 0Ý  ÷÷ ñ õ >ôO.�:õ O.r   