o
    sgqp                     @   s  d Z 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
 ddlmZ ddlmZ ddlmZ ddlmZ dd	l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 ddl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, ddl-m.Z. ddl/m0Z0 e  ej1d Z2dZ3G dd deZ4G dd dZ5e6dkrdgZ7e7D ].Z8e5e8ddZ9e9:d  e9j;j<dure9:d! e9j=>e9j;j? d" e@e9j;j? d# qdS dS )$z'Create a ppt with the given information    N)load_dotenv)ChatPromptTemplate)JsonOutputParser)
ChatOpenAI)	ImageFont)	MSO_SHAPE)InchesPt)	BaseModel)OPENAI_MODEL_35)CompanyProfileMakerfind_llm_response)CompanyInfo)
LLMResults)ChartCreator)CompanyOverview)DefaultSettingsSlideWorkArea)slide_layouts_choicesslide_layouts_choices_keys)DownloadImage)GoogleSearch)
parsed_urlGOOGLE_SEARCH_APIzppt_templates/ppt_template.pptxc                   @   s6   e Zd ZU dZee ed< ee ed< ee ed< dS )NewArticleszNew articlesarticlesarticles_summaryarticles_linksN)__name__
__module____qualname____doc__liststr__annotations__ r%   r%   H/var/www/html/XCapMarket/services/ppt_generator/company_profile_slide.pyr   -   s
   
 r   c                   @   s   e Zd ZdZde e ddfdedejdedede	d	e
fd
dZdd Z	d6dedefddZdd ZedefddZdd ZdefddZdd Zd7d d!Zd"d# Zd$d% Zd8d'd(Zd)e	fd*d+Z		d9d,ed-ed.efd/d0Zd1d2 Zd3e	fd4d5ZdS ):CompanyProfileSlidez&Create a slide for the company profileNFcompany_url
ppt_object	work_areadefault_settingscomparable_tickersnew_deckc                 C   s  || _ | j du r|rtt| _ || _|| _| jdu r g d| _|j| _|j| _	|j
| _t|| _| jj| _|   t| jj| jj| jjt| j d dt| j d d| jjd t| j d dt| j d dt| j d dd	 t| j d d
 d	| _d| _dS )a6  
        Create a ppt with the given information
        ppt_object: the ppt slide object
        company_url: the company url
        work_area: the work area for the slide
        default_settings: the default settings for the slide
        comparable_tickers: the comparable tickers for the company
        N)z^DJIz^SPXz^IXICLLM_results	CustomersProducts
leadership
HQ_FoundedOverview
Overview_Stats)	company_namelogostock_ticker	customersproducts
managementhqfoundedoverview )prspptxPresentationPRES_TEMPATEr*   r,   fontdefault_font	font_sizedefault_font_size
font_colordefault_font_colorr   urlr(   get_datar   company_infor6   r7   r8   r   llm_results
model_dumpr1   company_overviewrelevant_news)selfr(   r)   r*   r+   r,   r-   r%   r%   r&   __init__7   sR   





zCompanyProfileSlide.__init__c              
   C   s   t | j| _t| j| _| jjdu r&t| j| _	t
| j	j| jd| _| jjr@t| jjdt
| | jjjd| jjj | jjdu rat| j| _	t| j d d}t
| j	|| j_t
|   dS )zGet the data from the databaseN)supplied_company_infoimg_locr7   r.   
Leadership)r   get_company_infor(   rL   r   get_LLM_resultsrM   r7   r   rO   asynciorun
load_brandsetattrdownload_imagelogo_url	logo_darkr1   r   rN   map_leadershipsearch_management_pictures)rQ   company_leadership_textr%   r%   r&   rK   z   s<   
zCompanyProfileSlide.get_dataT	image_url	file_namec                    sD   t  }|dkr|j}|j|| jj d| d|dI dH \}}|S )z&Download the logo from the company urlr?   _z.png)rJ   rc   picture_background_darkN)r   STOCK_IMAGE_FILENAME	get_imagerL   r6   )rQ   rb   rc   dark_backgrounddird   	image_locr%   r%   r&   r\      s   z"CompanyProfileSlide.download_imagec                    s  g }| j jd D ]}t }|t|jd| jj d|j	 dddddd	 q	tj
| I d
H }g }|D ]}g }|D ]}d|d v rH|| q;|D ]}	||	 qKq5t| j jd D ]H\}
}t||
 dkrkd}n||
 d d }||
 D ]}|d |d  }d|  k rdk rn qw|d } nqwt| ||j	d}|| q\tj
| I d
H }t| j jd D ]\}
}t|d||
  q| j jS )z7Search for the image of the management person on googler1   "z" "z" headshot squareimagesTzlinkedin.comd   )domain_checkdomain_name_to_checknum_of_resultsNz?https://static.licdn.com/aero-v1/sc/h/1c5u578iilxfi4m4dvc4q810qimageUrlr   r?   
imageWidthimageHeightg?g333333?FrT   )rM   r1   r   appendrX   create_tasksearch_googlerL   r6   namegatherremove	enumeratelenr\   r[   )rQ   search_tasksleadergoogle_searchresults_of_resultsimage_resultsresultsitems_to_removeresultitemirb   image_aspect_ratiotaskr%   r%   r&   r`      sd   
z.CompanyProfileSlide.search_management_picturesllm_response_categoryc                 C   s&   ddddddd}| |vrdS ||  S )z>Convert the llm response category to the company info categoryr:   r;   r9   r>   r<   )r0   rU   r/   r5   r3   r2   Nr%   )r   llm_to_ci_mappingr%   r%   r&   convert_llm_to_ci   s   	z%CompanyProfileSlide.convert_llm_to_cic                 C   s>   | j jD ]}|j|kr|tv rt| }nd}||f  S qdS )zGet the slide layout by name
        input:
        - layout_name: the name of the layout to get
        output:
        - layout: the layout
        - slide_structure: the structure of the slide
        NNN)r@   slide_layoutsrw   r   )rQ   layout_namelayoutslide_structurer%   r%   r&   get_slide_layout  s   

z$CompanyProfileSlide.get_slide_layoutslide_to_createc              
   C   s   |t vrt| d| |\}}z>| jj|}|dkr'| || W |S |dkr6| j||dd W |S |dkrN| || j	j
| j	j|d |d  W |S W |S  tyg } zt| W Y d	}~d	S d	}~ww )
zCreate the slides for the pptz not in slide_layouts_choicesprivate_company_profilestock_chart_output   )years_to_showextra_contentheadercontentN)r   
ValueErrorr   r@   slides	add_slidecreate_private_company_profileadd_stock_chart_slideextra_content_sliderO   r6   r7   	Exceptionprint)rQ   r   r   r   slideer%   r%   r&   create_slides  s6   z!CompanyProfileSlide.create_slidesc                    s  |j D ]}|j}||v r|| d dkr/|| d dkrq |t j|| d ||  q|| d dkr?|| d |_
q|| d dkrQ | jj| q|| d dkr{t jj|| d krz jj|| d  }|jdurz||j q|| d dkrt jj|| d kr jj|| d  }|jjd  }|j|_
d|j_|jjd  }d|j |_
qt jjdkr҈ d jj jjd jj dS dS )zCreate the slidefieldr   datanewsNr?   r4   c                    s&   g | ]\}}| d  j j|  qS )z: )rP   r   ).0r   titlerQ   r%   r&   
<listcomp>S      zFCompanyProfileSlide.create_private_company_profile.<locals>.<listcomp>zNews Links:
z

c                    s&   g | ]\}} j j|  d | qS )r4   )rP   r   )r   r   linkr   r%   r&   r   _  r   r   
logo_imageleader_pictureleader_namer   T   r   rU   )placeholdersrw   rP   write_contentjoinrz   r   r   notes_slidenotes_text_frametextgetattrrO   add_logor7   r{   r;   rT   insert_picture
text_frame
paragraphsadd_runrD   boldr   add_leadershipr6   )rQ   r   r   place_holder	item_namer}   rY   r%   r   r&   r   7  sd   
)








z2CompanyProfileSlide.create_private_company_profiler   c              
   C   s   |j D ]t}|j}||v rw|| d dkr&| |t| j|| d ||  q|| d dkr6|| d |_q|| d dkrH| || jj| q|| d dkrwt }|j	| j
j|| jd}|j||j|j|j|j|dd	 |j |j qd
S )zadd the stock chart slidesr   r   r   r   r   stock_chart)other_tickersdate)x_axisN)r   rw   r   r   rO   r   r   r7   r   get_stock_datarL   r8   r,   add_line_charttopleftwidthheightelement	getparentry   )rQ   r   r   r   r   r   chart_creatorstock_data_dfr%   r%   r&   r     sD   
	
z)CompanyProfileSlide.add_stock_chart_slidec                 C   s   |du r	d|_ dS |jj|j|j|j|jd}|j 	|j |j
|j
kr>|j
|j
 }t|j
| |_
t|j| |_dS dS )zOAdds the logo in place of the placeholder and resizes it to fit the placeholderNzNo Logo Found)r   r   r   )r   shapesadd_picturerT   r   r   r   r   r   ry   r   int)rQ   r   	logo_item	slide_objnew_picrescaler%   r%   r&   r     s   zCompanyProfileSlide.add_logoc                 C   s   | dd}| j||jtd td td |jtd |d  |d |d d	\}}||_|rB| d
| jj| jj	|d | dS dS )z$Write the content to the placeholderz- r?         ?皙?   height_multiplierrF   	font_type)max_width_pxmax_height_pxrF   rD   r   r   N)
replaceestimate_text_sizer   r	   r   r   r   rO   r6   r7   )rQ   r   r   content_attributestext_to_writetext_over_heightr%   r%   r&   r     s(   
z!CompanyProfileSlide.write_contentr?   c                 C   s   |  |\}}| jj|}| d| d|_| }|jD ]3}	|	j}
||
ddurQ||
 d dkr>t ||
 d  |	_	q||
 d dkrQ|durQ| 
|	|| q|S )zCreate an extra content sliderd   _extra_contentNr   r   r   image)r   r@   r   r   rw   
capitalizer   getlocalsr   r   )rQ   
slide_namer6   r7   r   r   r   r   r   r   r   r%   r%   r&   r     s   
z'CompanyProfileSlide.extra_content_slider1   c                 C   st  |  ||||}|jD ]}|jdkr|j}|j}	|D ]}
z{|jj|
j|	|tdtdd}t	j
|_||j td }|	}td}td}|j||||}d|j_|jjd  }|
j|_td|j_d|j_|jjd  }d	|
j |_td|j_|	td
kr|td7 }|j}	n
|	tdtd 7 }	W q ty } z
t| W Y d}~qd}~ww |j |j q|S )zAdd the leadership to the slidezContent Placeholder 1gQ?)r   r   r   r   g?gzG@Tr      r4   r   g      @r   N)r   r   rw   r   r   r   r   rT   r   r   OVALauto_shape_typer   add_textboxr   	word_wrapr   r   r   r	   rD   sizer   r   r   r   r   r   ry   )rQ   r   r6   r7   r   r1   r   r   content_leftcontent_topr}   r   r   r   r   r   txBoxrY   r   r%   r%   r&   r     sR   

	z"CompanyProfileSlide.add_leadershipr   r   r   c                 C   s   |du r| j }|du r| j}t||}|d}g }d}	|D ]*}
|
dks)|
du r*qt||
 d | | d }||krE|	|
 ||8 }q|dk rPd}	d
||	fS )	a  
        estimate the size of a text body
        input:
        - text: the text to estimate
        - max_width_px: the max width of the text in pixels
        - max_height_px: the max height of the text in pixels
        - font: the font to use
        - font_size: the font size to use

        output:
        - text_to_draw: the text to draw
        - text_over_height: if the text is over the height
        Nr4   Fr?      g      ?r   T)rE   rG   r   truetypesplitmathceilgetmaskgetbboxrt   r   )rQ   r   r   r   rD   rF   fnt
text_linestext_to_drawr   lineline_heightr%   r%   r&   r   J  s.   


z&CompanyProfileSlide.estimate_text_sizec                 C   s8   t  }t|| jj d}t|dkrdS | |S )zGet the company newsr   r   N)r   rX   rY   rv   rL   r6   r{   filter_news)rQ   rv   r   r%   r%   r&   get_company_news  s   
z$CompanyProfileSlide.get_company_newsr   c                 C   s   t ttjd dd}tg d}ttd}||B |B }|| j	j
| j	j| jjt|| d}z
tdi |}W |S  tys   td || j	j
| j	jrU| j	jnd| jjtd	d
 |D | d}tdi |}Y |S w )zFilter the newsOPENAI_API_KEYr   )modelapi_keytemperature))systemag  
            You are going to be given news articles with the title and snippet. You need to determine if the news is relevant to your client.
            You need to return the articles that are relevant, with a summary and the link to the article.
            Make sure the article is relevant to the company and industry you are working with.
             )humanzqThe company you are working with is {company_name} in the {industry} industry with an overview of this {overview})r  z
{articles})r  zTOutput format should be: {json_structure} and give me atleast 5 articles if not more)pydantic_object)r6   industryr>   r   json_structurer   r?   c                 S   s$   g | ]}|d  |d |d dqS )r   snippetr   )r   r  r   r%   )r   articler%   r%   r&   r     s    z3CompanyProfileSlide.filter_news.<locals>.<listcomp>Nr%   )r   r   osenvironr   from_messagesr   r   invokerL   r6   r  rO   r>   jsondumpsget_format_instructionsr   timesleep)rQ   r   llmpromptparserchainoutputr%   r%   r&   r     sL   



zCompanyProfileSlide.filter_news)T)r   )r?   r   )r   r   r    r!   r   r   r#   rA   rB   r"   boolrR   rK   r\   r`   staticmethodr   r   r   r   r   r   r   r   r   r   r   r   r   r   r%   r%   r%   r&   r'   4   sb    
C'
A 
k+
=
7r'   __main__z	unity.comT)r(   r-   r   r   z_company_profile.pptxz PPT created)Ar!   rX   r  r   r
  r  rA   dotenvr   langchain.promptsr   langchain_core.output_parsersr   langchain_openair   PILr   pptx.enum.shapesr   	pptx.utilr   r	   pydanticr
   configs.configr   (services.company_profile.company_profiler   r   2services.company_profile.data_classes.company_infor   1services.company_profile.data_classes.llm_resultsr   $services.ppt_generator.chart_creatorr   4services.ppt_generator.data_classes.company_overviewr   *services.ppt_generator.layouts.xcm.layoutsr   r   ,services.ppt_generator.slide_layouts_choicesr   r   utils.download_imager   utils.search_googler   utils.url_parserr   r  r   rC   r   r'   r   urlsrJ   pptgr   rL   r8   r@   saver6   r   r%   r%   r%   r&   <module>   sf    
     %

