
    th3                         d dl Z d dlZd dlZd dlmZmZmZmZ d dlm	Z	 d dl
mZ d dlmZmZ d dlmZmZ d dlmZmZ d dlmZ d d	lmZ  ej0                  e      Z G d
 d      Zy)    N)DictAnyListOptional)AzureOpenAI)Session)funcand_)datetimetimezone)CalendarPostCalendarPostType)StorePersona)schemac                   F   e Zd ZdZd Z	 ddededee   dej                  fdZ
	 ddededee   dee   fd	Zddededee   deeef   fd
Zdeeef   deeef   fdZdeeef   defdZdedeeef   fdZdededee   deeef   def
dZdedej*                  fdZy)AzureLLMPersonaServicez9Service for generating store personas using Azure OpenAI.c                     t        t        j                  d      t        j                  dd      t        j                  d            | _        t        j                  dd      | _        y )NAZURE_OPENAI_API_KEYAZURE_OPENAI_API_VERSIONz2024-02-15-previewAZURE_OPENAI_ENDPOINT)api_keyapi_versionazure_endpointAZURE_OPENAI_DEPLOYMENTgpt0)r   osgetenvclientdeployment_name)selfs    E/var/www/html/hubwallet-dev/src/marketing/apps/persona/llm_service.py__init__zAzureLLMPersonaService.__init__   sN    !II45		"<>RS99%<=

  "yy)BFK    Ndbstore_id	branch_idreturnc           	      x   	 | j                  |||      }|r't        j                  dd| j                  |            S | j	                  |||      }|st        j                  dd      S |j                  d      st        j                  dd      S | j                  |      }| j                  ||||      }t        j                  dd	| j                  |      |
      S # t        $ rQ}t        j                  d| dt        |              t        j                  ddt        |             cY d}~S d}~ww xY w)z0Generate persona for a store based on post data.TzPersona already exists)successmessagedataFzNo post data found for analysis)r)   r*   post_contentzYNo post content found for analysis. Please ensure posts have content in CalendarPostType.zPersona generated successfully)r)   r*   r+   analysis_metadataz#Error generating persona for store z: zError generating persona: N)_get_existing_personar   PersonaGenerationResponse_build_persona_response_get_store_post_dataget_analyze_with_llm_create_persona	Exceptionloggererrorstr)	r    r$   r%   r&   existing_persona	post_datapersona_datapersonaes	            r!   generate_persona_for_storez1AzureLLMPersonaService.generate_persona_for_store   sH   +	#99"h	R77 4556FG  11"h	JI77!=  ==077!w   11)<L **2xLQG33811':".	   	LL>xj3q6(ST334SVH= 	s0   ;C +C *'C AC 	D9(AD4.D94D9c                    	 |j                  t              j                  t        j                  |k(        }|r#|j                  t        j                  |k(        }n.|j                  t        j                  j                  d            }|j                  t        j                  dk(        j                         S # t        $ r}t        j                  dt        |              	 |j                  t              j                  t        j                  |k(        }|r#|j                  t        j                  |k(        }n.|j                  t        j                  j                  d            }|j                         cY d}~S # t        $ r/}t        j                  dt        |              Y d}~Y d}~yd}~ww xY wd}~ww xY w)z&Get existing persona for store/branch.NTz1Error querying existing persona (schema issue?): zFallback query also failed: )queryr   filterr%   r&   is_	is_activefirstr5   r6   warningr8   r7   )r    r$   r%   r&   r@   r=   e2s          r!   r.   z,AzureLLMPersonaService._get_existing_personaP   sN   	HH\*11,2G2G82STE\%;%;y%HI\%;%;%?%?%EF<< 6 6$ >?EEGG 	NNNsSTvhWX.55l6K6Kx6WX!LL)?)?9)LME!LL)?)?)C)CD)IJE{{}$ ;CG9EFt	sC   B7B: :	G!F=%BF<G	F:!F5,F=5F::F==Gc                    |j                  t        t              j                  t              j	                  t        j
                  |k(  t        j                  dk(  t        j                  dk(        }|r"|j	                  t        j                  |k(        }|j                  d      j                         }|si S t        d |D              }|s,t        j                  d|        g g g t        |      ||g g dS t        j                  dt        |       d| dt        |D cg c]  \  }}|j                  s| c}}       d	       g }	g }
g }|D ]  \  }}|j                  r|	j!                  |j                  d
d        |j"                  r|
j!                  |j"                         |j                  sd|j!                  |j                  d
d |j"                  |j$                  r|j$                  ndd        |	d
d t'        t)        |
            |d
d t        |      |||D cg c]  \  }}|j$                  s|j$                    c}}d
d |D cg c]  \  }}|j*                  s|j*                    c}}d
d d}t        j                  dt        |	       dt        t)        |
             d       t        j-                  d|	r|	d
d nd        |S c c}}w c c}}w c c}}w )zGet post data for LLM analysis.F2   c              3   :   K   | ]  \  }}|j                     y wN)content).0_	post_types      r!   	<genexpr>z>AzureLLMPersonaService._get_store_post_data.<locals>.<genexpr>   s     F9)++Fs   z$No content found in posts for store )r,   
post_typesengagement_datatotal_postsr%   r&   post_titles
post_dateszFound z posts for store , z with contentN   d   zNo Title)rK   rN   title   
   zPost data summary: z content items, z post typeszSample content:    None)r@   r   r   joinrA   r%   
is_deletedr&   limitallanyr6   rE   leninforK   appendrN   rX   listsetschedule_datedebug)r    r$   r%   r&   r@   postshas_contentrM   pr,   rP   rQ   postrN   result_datas                  r!   r1   z+AzureLLMPersonaService._get_store_post_datap   s   '78==>NOVV!!X-##u,''50
 LL!7!79!DEEB##%I FFFNNA(LM " #%"5z$&! 	 	 	fSZL(9(2cY^JlQUQRTUbcbkbk1JlFmEnn{|} 
$ 	OD)  ##I$5$5ds$;<""!!)"5"56   &&(00#6!*!4!4+/::TZZ:( 	  )"-s:/.s3u: "6;J74tzzDJJJ3BO=BY'$dFXFX4--YZ][]^	
 	)#l*;)<<LSQTU_Q`MaLbbmno'LRa(8f'UVWI Km: KYs$   "K7K(K =K K&+K&r:   c                    	 | j                  |      }| j                  j                  j                  j	                  | j
                  dddd|dgdd      }|j                  d   j                  j                  }| j                  |      }||d	d
S # t        $ r6}t        j                  dt        |              dddddddd
cY d}~S d}~ww xY w)z9Analyze post data using Azure OpenAI to generate persona.systemzYou are an expert brand analyst. Analyze the provided social media post data and identify the store's brand persona. Be concise and specific.)rolerK   userg333333?i  )modelmessagestemperature
max_tokensr   g333333?)analysis_textr;   confidence_scorezError in LLM analysis: z&Analysis failed, using default personaGeneral RetailGeneral ConsumersProfessionalInformativeindustryaudience_typebrand_voicecontent_styleg      ?N)_create_analysis_promptr   chatcompletionscreater   choicesr*   rK   _parse_llm_responser5   r6   r7   r8   )r    r:   promptresponserv   r;   r=   s          r!   r3   z(AzureLLMPersonaService._analyze_with_llm   s   +	11)<F {{''33::** !) $s
 !'#)	   ; H" %,,Q/77??M33MBL "/ ,$(   	LL23q6(;< "J 0%8#1%2	! %(	 		s   BB 	C+CCCc                    d|d    d|d    ddj                  |d          dt        d	      j                  |d
   dd        dt        d	      j                  |j                  dg       dd        dt        d	      j                  |j                  dg       dd D cg c]  }t        |       c}       d}|S c c}w )z'Create the analysis prompt for the LLM.zS
Analyze this social media data and identify the store's brand persona:

Store ID: r%   z
Total Posts: rR   z
Post Types: rU   rP   z

Sample Post Content:
rZ   r,   N   z

Post Titles (if available):
rS   z

Post Schedule Dates:
rT   a  

Based on this data, identify:
1. Industry: What industry does this store operate in?
2. Audience Type: Who is their target audience?
3. Brand Voice: What is their communication style?
4. Content Style: How do they present their content?

Respond in this exact JSON format:
{
    "industry": "industry name",
    "audience_type": "audience description",
    "brand_voice": "voice description",
    "content_style": "style description"
}
)r]   chrr2   r8   )r    r:   dater   s       r!   r   z.AzureLLMPersonaService._create_analysis_prompt   s     Z 
! "&' (YYy./0 1 Ri'+, - . RimmM2.r23 4 5 RY]]<%DRa%HITs4yIJ K L< ! Js   B;response_textc                    	 d|v rd|v r|j                  d      }|j                  d      dz   }||| }t        j                  |      }|j	                  dd      |j	                  dd      |j	                  dd	      |j	                  d
d      dS ddd	ddS # t
        $ r+}t        j                  dt        |              Y d}~6d}~ww xY w)z+Parse LLM response to extract persona data.{}   r}   Generalr~   ry   r   rz   r   r{   r|   zError parsing LLM response: Nrx   )	findrfindjsonloadsr2   r5   r6   r7   r8   )r    r   startendjson_strr+   r=   s          r!   r   z*AzureLLMPersonaService._parse_llm_response  s    	Bm#}(<%**3/#))#.2(s3zz(+ !%Y ?%)XXo?R%S#'88M>#J%)XXo}%M	  )0)*	
 	
	  	BLL7Ax@AA	Bs   BB 	C !CCr;   c                    t        |||d   d   |d   d   |d   d   |d   d   |d   |d   t        j                  t        j                        	      }|j                  |       |j                          |j                  |       |S )	zCreate new persona record.r;   r}   r~   r   r   rv   rw   )	r%   r&   r}   r~   r   r   analysis_summaryrw   last_analyzed)r   r   nowr   utcaddcommitrefresh)r    r$   r%   r&   r;   r<   s         r!   r4   z&AzureLLMPersonaService._create_persona!  s     !.1*=&~6G$^4]C&~6G)/:)*<=",,x||4

 	w
		


7r#   r<   c                 J   t        j                  |j                  |j                  |j                  |j
                  |j                  |j                  |j                  |j                  |j                  |j                  |j                  |j                  |j                        S )z#Build response from database model.)idr%   r&   r}   r~   r   r   r   rw   r   
created_at
updated_atrC   )r   StorePersonaResponser   r%   r&   r}   r~   r   r   r   rw   r   r   r   rC   )r    r<   s     r!   r0   z.AzureLLMPersonaService._build_persona_response;  s    **zz%%''%%!//++!//$55$55!//))))''
 	
r#   rJ   )__name__
__module____qualname____doc__r"   r   intr   r   r/   r>   r   r.   r   r8   r   r1   r3   r   r   r4   r   r0    r#   r!   r   r      sn   CL $(	22 2 C=	2
 
	)	)2p $(	  C=	
 
,	@Cw C# C(SV- Ccghkmphpcq CJ-4S> -d38n -^ c3h  C  D
 
c3h 
6  C=	
 38n 
4
| 
@[@[ 
r#   r   )r   r   loggingtypingr   r   r   r   openair   sqlalchemy.ormr   
sqlalchemyr	   r
   r   r   src.marketing.apps.post.modelr   r    src.marketing.apps.persona.modelr   src.marketing.apps.personar   	getLoggerr   r6   r   r   r#   r!   <module>r      sG    	   , ,  " ! ' H 9 -			8	$z
 z
r#   