o
    sg _                     @   s  d Z ddlZddlZddlZddlZddlmZmZ ddlmZm	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T ddlmZmZmZmZ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+ ddl,m-Z- ddl.m/Z0 ddl1m2Z2 e3 Z4G dd dZ5e6dkrddlm7Z7 ddl*m+Z+ e+ Z8e89e8j:dZ;e7di e;Z;e;j<=d e>e; e5e;e;j?Z@e@A  e;jB deC Dd ZEdeE ZFe@jGHeF dS dS ) zConvert structure to pptx    N)ThreadPoolExecutoras_completed)datetimetimezone)ChatPromptTemplate)JsonOutputParser)
ChatOpenAI)OPENAI_MODEL_MINI)CompanyInfo)CompanyProfileSlide)SectionSlide)*)
CompsTableDefaultSettingsFullPage
SideBySideSlideWorkArea	TopBottom)AcquisitionsRecommender)PublicComparables)ChromaDB)ClientConfig)DynamoDB)InternalSearch)
Researcher)
parsed_urlc                   @   s   e Zd ZdZdZdZdZdZd0d1ddZdd	 Z	d
d Z
dedefddZdededefddZdd Zd0ddZdd ZdefddZdd Zdd Zd d! Zd"d# Zd$d% Zd&d' Zd(d) Zd*d+ Zd,d- Zd.d/ ZdS )2	CreatePPTz Create a pptx from the structurezppt_templates/ppt_template.pptxN returnc                 C   s   || _ || _t | _t | _|r6| jj| _| jj| _t| jjd}| | _W d   n1 s1w   Y  t	
| j| _|| _|jrH|j| _ng | _|j| _|j| _|j| _dS )zInitialize the pptx object.rN)main_companyclient_configr   slide_work_arear   default_settingsopenlayout_choicesreadpptxPresentationPPT_TEMPLATEprsprojectsectionsslides_structuretargetscompany_namecompanycompany_url)selfr,   r!   r"   f r5   =/var/www/html/XCapMarket/services/ppt_generator/create_ppt.py__init__0   s$   


zCreatePPT.__init__c           	   	   C   s   ddl m} tddd|j fdd|j fdd|jpd d	fd
dg}tt	dt
dd}t|d}||B |B }|| j| d}|di |}|S )zSBased on the layouts that the client has, find the appropriate layout for the slider   )SlideContent)systemz%You are an powerpoint slide desginer.humanz%The slide we are creating is titled: zThe content of the slide is: z'The information you have gathered is 
 r   z 
)r:   z:Choose from the following layout options: {layout_options})r9   z2You will respond in a json object as {json_output}OPENAI_API_KEY      ?api_keymodeltemperaturepydantic_object)layout_optionsjson_outputNr5   )8services.ppt_generator.data_classes.presentation_outliner8   r   from_messagestitlecontentresearchr   osgetenvr	   r   invoker&   get_format_instructions)	r3   slider8   chat_promptllmparserchainchain_outputresponser5   r5   r6   find_appropriate_layoutN   s4   
z!CreatePPT.find_appropriate_layoutc                 C   s   |j }|j j|j7  _dS )zAdd research to the slidesN)notes_slidenotes_text_frametextrI   )r3   	prs_sliderN   rV   r5   r5   r6   add_research_to_slidest   s   z CreatePPT.add_research_to_slides
slide_infosectionc                 C   sL  ddl }|  }t| j| jd}| }|rCtd|j |j|j	d
|j d}td|j|  |  | ||\}}	td|	 |	d	u sK|d
u rc|  }
|| ||7 }td|j|  |
  | |||}|sndS ||_| jjD ]}|j|jkr|jD ]}|j|jkr||_qqu| j  |  }td|j d||  d |S )zConduct research for the slide.r   N)r,   clientz!Conducting research for slide: %s
)questionz7Internal research for slide: %s completed in %d secondsz!Do we need external research?: %sTFz8Secondary research for slide: %s completed in %d secondszConducted research for z took z seconds)timer   r,   r"   project_contain_docs
XCM_loggerinforG   break_down_question_and_answerrH   join	questionsexternal_research_requiredprintget_secondary_research_store_research_in_dynamodbrI   r-   uuidslidesupdate_project_in_db)r3   r[   r\   r`   startprimary_researcherinternal_docs_existresearch_combinednew_research_questionsneeds_new_researchget_secondary_startitem_id_sectionrN   endr5   r5   r6   conduct_researchy   s\   





zCreatePPT.conduct_researchrI   rN   c              
   C   s   t  }t| jj|j|j}|| jj|j|j|ttj	
 ttj	
 d}z||d| |W S  tyN } ztd|  W Y d}~dS d}~ww )zStore research in dynamodb)id
project_idslide_idr\   rI   
created_at
updated_atslides_researchz$Error storing research in DynamoDB: N)r   r   build_slide_research_idr,   rz   rk   r   nowr   utc	isoformatupload_to_dynamodb	get_table	Exceptionrh   )r3   rI   rN   r\   dbru   itemer5   r5   r6   rj      s(   	z%CreatePPT._store_research_in_dynamodbc                 C   sF   t dd| || jj d| jj d| jj d}| }d| S )z?Conduct secondary research if additional information is needed.zquestions to answer: z, 
z Investment Banker making a z for )parent_questionprimary_researchpersonaz


From Internet:
)ResearcherV2re   r,   industry
pitch_typer0   rx   )r3   rr   r   secondary_researchersecondary_researchr5   r5   r6   ri      s   
z CreatePPT.get_secondary_researchc           	      C   s~   G dd dt }tg d}t|d}ttdtdd}||B |B }||j	|j
|| d}|d
i |}|j|jfS )z&Check if external research is requiredc                   @   s:   e Zd ZU eg ddZee ed< edddZe	ed< dS )z?CreatePPT.external_research_required.<locals>.research_requiredzThe new research questions)defaultrG   rr   FzWhether new research is neededrs   N)
__name__
__module____qualname__Fieldrr   liststr__annotations__rs   boolr5   r5   r5   r6   research_required   s   
 r   ))r9   zrYou are an expert AI researcher skilled in understanding if it would be helpful to source information from Google.)r:   z2The slide we are creating is titled: {slide_title})r:   z,The content of the slide is: {slide_content})r:   z;The information you have gathered is 
 {primary_research} 
)r:   zhDo you need to conduct an internet search to get more information? True or False. Only return the answer)r:   zYou will want to conduct research for competitors, industry, or other generally publicly available information informationt that could help.)r9   z:You are going to respond in a json object as {json_output}rA   r;   r<   r=   )slide_titleslide_contentr   rD   Nr5   )	BaseModelr   rF   r   r   rJ   rK   r	   rL   rG   rH   rM   rr   rs   )	r3   rN   r   r   rO   rQ   rP   rR   rS   r5   r5   r6   rg      s(   
	z$CreatePPT.external_research_requiredc                 C   s   | j }t| j|dd}| | | || | jD ]R}|jD ]L}z|j| |d}| 	|| | 
|| W n" tyZ } zt| tjd|j| jjdd W Y d}~qd}~ww | | | j  | | qq| | | | | | | jS )zConvert the structure to pptFr2   
ppt_objectnew_deck
title_onlyz)Error in creating slide: %s 
 Project: %sT)exc_infoN)r+   r   r2   beginning_slidecreate_company_profiler.   rl   	add_slideget_slide_layoutrZ   create_slider   rh   loggingerrorrG   r,   rz   save_pptrm   create_target_profilescreate_comps_pagesfilepath)r3   r+   company_profile_slider\   rN   rY   r   r5   r5   r6   convert_structure_to_ppt  sF   








z"CreatePPT.convert_structure_to_pptc              
   C   sD  |j D ]}|jjdkr|j|_|j|_| ||_|jjdv r9t	|| j
|jj| j|| j|jd}|  |  q|jjdkrYt|| j
|jj| j|| j|jd}|  |  q|jjdv rt|jj dkrtd t|jj d }||jj| i|j_t|| j
|jj| j|| j|jd}|  qtd tdqd	S )
zCreate the slider   )zLayout AzLayout B)r"   rI   zLayout C)zLayout DzLayout EzLayout FzLayout GzLayout HzLayout I   z%More than one content layout providedzLayout not foundN)placeholdersplaceholder_formatidxrG   rX   namerU   content_layoutlayoutr   r#   information_to_provider,   r"   rI   	left_side
right_sider   top_halfbottom_halflenkeysrh   r   r   add_content
ValueError)r3   rY   rN   placeholderslide_creatorr[   r5   r5   r6   r   E  sn   
	
	


	zCreatePPT.create_slidec                    s   t dt d }fdd t|d" fddjjD }t|D ]}| \}}q%W d   dS 1 s9w   Y  dS )	zJConduct research for the presentation using multi-threading for API calls.      c                    s   t  jj|j| j}dd }t| ddr)|t| dkr"| ||fS | t| dfS t| di durN| jddrN|| jdkrF| ||fS | | jdfS d}||}|rZ| |fS |  | |fS )z,Function to fetch research data for a slide.c                 S   s0   t  }||d| }|d ur|ddS dS )Nr~   rI   r   )r   get_itemr   get)research_item_idr   r   r5   r5   r6   get_research_from_dynamodb  s
   zbCreatePPT.research_presentation.<locals>.conduct_research_task.<locals>.get_research_from_dynamodbrI   Nextrar   )	r   r   r,   rz   rk   getattrr   r   rx   )rN   r\   r   r   research_from_dynambo)r3   r5   r6   conduct_research_task  s$   z>CreatePPT.research_presentation.<locals>.conduct_research_task)max_workersc                    s(   i | ]}|j D ]
} |||qqS r5   )rl   submit).0r\   rN   )r   executorr5   r6   
<dictcomp>  s    z3CreatePPT.research_presentation.<locals>.<dictcomp>N)minrJ   	cpu_countr   r,   r-   r   result)r3   r   futuresfuturerN   rI   r5   )r   r   r3   r6   research_presentation  s   "zCreatePPT.research_presentationc                 C   s.   | d |jjd ur| d | | d S )Nprivate_company_profilestock_chart_output)create_slidescompany_infostock_tickerr   )r3   r+   r   r5   r5   r6   r     s   

z CreatePPT.create_company_profilec                 C   sZ   | j r&t| j ddr&td| j j d}t|dr&||d| j}|  | 	| dS )zCreate the beginning slidelayout_fileNzservices.ppt_generator.layouts.z.layoutsBeginningSlideszBob Cool)
r"   r   	importlibimport_moduler   hasattrr   r,   mainr   )r3   r+   client_module
beg_slidesr5   r5   r6   r     s   

zCreatePPT.beginning_slidec                 C   s"   |j D ]}|j|kr|  S qdS )z)Get the slide layout from the layout nameN)slide_layoutsr   )r3   r+   layout_namer   r5   r5   r6   r     s
   

zCreatePPT.get_slide_layoutc                 C   sr   | j sdS | | j }| |}| j||dd |d D ]}|d D ]}t||dd}|d q"q| | dS )	zCreate the target profilesNz&Potential acquisition target landscape)rG   groups	companiesFr   r   )r/   group_companiescreate_gridcreate_landscaper   r   r   )r3   r+   company_groupsgrid_detailsgroupr1   r   r5   r5   r6   r     s"   
z CreatePPT.create_target_profilesc                 C   sb   g }|d D ](}|d |d g d}|d D ]}|}t |}|d |jj q|| q|S )z1Create the grid for the overview of the companiesr   
group_name	rationale)rG   rX   imagesr   r   )r
   get_company_infoappendlogologo_url)r3   r   r   r   grid_detailr1   r2   r   r5   r5   r6   r     s   
zCreatePPT.create_gridc                 C   sx   |j |jd }|jD ]}|jjdkr||_qt|t ddi| j	ddd}|j
j|t jt jt jt j|d dS )	z:Create a landscape slide for the overview of the companiesr   r   	full_pagegridNF)conduct_research_flag)topleftwidthheightr   )rl   r   r   r   r   r   rX   r   r   r,   
make_slider   r   r   r   r   )r3   r+   r   rG   rY   r   r   r5   r5   r6   r   
  s*   
	
zCreatePPT.create_landscapec           
      C   s~   t  }|jjt| jjdd d }g }|D ]}t|j}|jj|d}|||d d d qt }|j|||j	d}	|	S )z2Group the companies based on overview and products)ids	documentsr   )r2   product_description)acq_company_descriptionr   open_ai_model)
r   product_collectionr   r   r2   urlr   r   regroup_companiesopenai_llm_3)
r3   companies_to_group	chroma_dbacq_companytarget_companiesr1   r2   company_detailsacq_recommenderr   r5   r5   r6   r   #  s0   


zCreatePPT.group_companiesc                 C   s   | j jdu rdS t| j jdkrdS | jd r!| j j| jd  t| j j}| |d}|j|}|j	D ]}|j
jdkrAd|_q6t|| j|}| | dS )zCreate the comp pagesNr   r   r   zPublic Comparisions)r,   public_compsr   r!   r   r   r   rl   r   r   r   r   rX   r   r#   r   )r3   r+   r  slide_layoutrY   r   r   r5   r5   r6   r   C  s&   

zCreatePPT.create_comps_pagesc                 C   sV   | j du r| j d| jj dt d | _ | jdu r#d| j  | _|| j dS )zSave the pptN_%Y-%m-%dppt_templates/finalized/%s.pptx)	filenamer1   r,   r   r   r   strftimer   save)r3   r+   r5   r5   r6   r   a  s
   
&
zCreatePPT.save_ppt)N)r   N)r   r   r   __doc__r*   r  r   r&   r7   rU   rZ   r   r   rx   r   rj   ri   rg   r   r   r   r   r   r   r   r   r   r   r   r   r5   r5   r5   r6   r   '   s>    &:

<3H0 r   __main__)Project
xcm_demo_1r   r  r  r  r5   )Ir  asyncior   r   rJ   concurrent.futuresr   r   r   r   r(   langchain.promptsr   langchain_core.output_parsersr   langchain_openair   configs.configr	   2services.company_profile.data_classes.company_infor
   ,services.ppt_generator.company_profile_slider   +services.ppt_generator.data_classes.projectr   r   7services.ppt_generator.data_classes.slide_layout_models*services.ppt_generator.layouts.xcm.layoutsr   r   r   r   r   r   -services.recommender.acquisitions_recommenderr   %services.stock_info.public_comparabler   utils.chroma_dbr   utils.client_checkr   utils.dynamo_dbr   !utils.researcher.chroma_search_v2r   utils.researcher.researcher_v2r   r   utils.url_parserr   	getLoggerrb   r   r   r  r   r   projectsr,   r-   poprh   r2   pptr   r0   r   r  r  r   r+   r  r5   r5   r5   r6   <module>   sZ         J