
    	j                     n    d Z ddlZddlmZmZ ddlmZmZmZ ddlZddl	m
Z
mZ deeef   deded	efd
Zy)u|   
Categorizer — orchestrates evidence building, scoring, and DB writes
for a single product within a categorization batch.
    N)datetimetimezone)ListDictAny)evidence_builderconfidence_scorerproductbatch_id	thresholdreturnc                 ^   |d   }| j                         5 }|j                  d||f       |j                         r
	 ddd       y	 ddd       | j                         5 }|j                  d|f       |j                         xs g }ddd       t	        j
                  t        |      D cg c]  }t        |       c}      }|st	        j                         g}t	        j                  |      }	t        j                  |      }
t        j                  |
|      }t        j                  t        j                        j!                  d      }| j                         5 }|j                  d|||	d   |	d	   |
|||f       |j                         d   }t#        d
 |D              }|D ]?  }t%        |j'                  dd      d      }|j                  d||d   |d   |d   ||f       A |j                  d||f       ddd       y# 1 sw Y   xY w# 1 sw Y   xY wc c}w # 1 sw Y   yxY w)a  
    Categorize a single product and write prediction + evidence to DB.

    Updates products.status = 'predicted' and the batch processed_products
    counter in the same call.  Caller is responsible for committing.

    Args:
        conn:       Open psycopg2 connection (autocommit=False).
        product:    Product DB row as a dict.
        batch_id:   ID of the parent categorization_batches row.
        threshold:  Confidence threshold from system_settings.

    Returns:
        True on success, False if the product was skipped (already predicted
        for this batch) or on recoverable failure.

    Raises:
        Exception: On unrecoverable DB errors.
    idzJSELECT id FROM predictions WHERE product_id = %s AND batch_id = %s LIMIT 1NFzTSELECT attribute_name, attribute_value FROM product_attributes WHERE product_id = %sz%Y-%m-%d %H:%M:%Sa:  
            INSERT INTO predictions
                (product_id, batch_id, suggested_category_code, suggested_category_label,
                 confidence_score, confidence_level, status, created_at, updated_at)
            VALUES (%s, %s, %s, %s, %s, %s, 'predicted', %s, %s)
            RETURNING id
            codelabelc              3   @   K   | ]  }|j                  d d        yw)weightg        N)get).0ss     4/var/www/html/ai_cats/python/services/categorizer.py	<genexpr>z%categorize_product.<locals>.<genexpr>_   s     AA1553/As   r   gMbP?   z
                INSERT INTO evidence
                    (prediction_id, source_type, source_label, evidence_value, weight, created_at)
                VALUES (%s, %s, %s, %s, %s, %s)
                source_typesource_labelevidence_valuezGUPDATE products SET status = 'predicted', updated_at = %s WHERE id = %sT)cursorexecutefetchonefetchallr   build_evidencedictfallback_signalpick_categoryr	   compute_scorederive_levelr   nowr   utcstrftimesumroundr   )connr
   r   r   
product_idcur
attributesasignalscategoryscorelevelr'   prediction_idtotal_weightsigws                    r   categorize_productr9      s=   2 J 
 #X"	
 <<> 
  
 *#bM	
 \\^)r
* --d7mz=Z!d1g=Z[G#3356  --g6H!//8E!..ui@EX\\*334GHC	 /
#  !		
& t, AAA 	Ccggh.2AKK "&'()	& 	U*	
Y/
b [ * * >[/
b s*   &H(H+H
BH#HH#H,)__doc__jsonr   r   typingr   r   r   psycopg2servicesr   r	   strintfloatboolr9        r   <module>rE      sV   
  ' " "  8i#s(^i i 	i
 
irD   