
    dhS                        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	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mZ d dlmZmZ d dlmZ ddlm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	 Zd
 Zd Zd Zd Zed        Zd Zd dlZd dlmZ d Zd dlZd dl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 Z%d dl mZ d Z&d dlZd dlZd dlmZ d dl mZmZ d dl'm(Z d dlmZ d Z)d dlZd dl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 d dl mZmZ d dlmZ d dlm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mZ d dlmZ d dlm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) ed        Z/d dlZd dlZd dlmZ d Z0d dl mZmZ d dlmZ d dlmZ d dlmZ d dlZd dlZed        Z1y)    )renderget_object_or_404)datetime	timedelta)Projeto   )CondicaoExtN)
connection)login_requiredc                 d    dt        j                  d| z  | dz   z        z  }||z  dz  | dz   z  }|S )Ng r@gQ1@g     pn@gͪV@gfffffq@)mathexp)temperaturaumidade_relativapressao_saturacaoumidade_absolutas       1/var/www/html/cagpublico/cag/condicaoext/views.pycalcular_umidade_absolutar      sH    %+*=+PUBU)V WW),<<vE+X^J^_    c                      t        j                         } | t        d      z
  }|j                  d      | j                  d      fS )Ni  )days%Y-%m-%d)r   nowr   strftime)data_fimdata_inicios     r   obter_periodo_ultimos_4_anosr      s=    ||~HYD11K
+X->->z-JJJr   c                    | j                   }| j                  }d}||||ddd}	 t        j                  ||      }|j	                          |j                         }d|vrt        j                  d| d| d	       y t        j                  |d   d
   |d   d   d      }	t        j                  |	d
         |	d
<   |	S # t        $ r"}
t        j                  d|
        Y d }
~
y d }
~
ww xY w)N-https://archive-api.open-meteo.com/v1/archivetemperature_2mAmerica/Sao_Paulolatitude	longitude
start_dateend_datehourlytimezoneparamsr'   /   Erro: Dados históricos não disponíveis para , .time)r.   r    Erro ao obter dados da API: )r#   r$   requestsgetraise_for_statusjsonloggingerrorpd	DataFrameto_datetime	Exception)projetor   r   r#   r$   urlr*   responsedatadfes              r   obter_temperaturas_periodor@   $   s    H!!I
9C!"'F<<F3!!#}}4MMKH:UWXaWbbcde\\N6*"8n-=>
  ^^BvJ/6
	 4QC89s   AB> =A B> >	C)C$$C)c                     | d   j                   j                  | d<   | j                  d      d   j                         }|j	                         }|j                         }||fS )Nr.   dater    )dtrB   groupbymaxidxmax)r>   max_temps_por_diadia_mais_quentetemperatura_maxs       r   identificar_dia_mais_quenterJ   F   s^    F##BvJ

6*+;<@@B'..0O'++-OO++r   c                    | j                   }| j                  }d}|||j                  d      |j                  d      ddd}	 t        j                  ||      }|j                          |j                         }d|vrt        j                  d| d	| d
       y t        j                  |d   d   |d   d   |d   d   d      }t        j                  |d         |d<   ||d   j                  j                  dk\  |d   j                  j                  dk  z     }|S # t        $ r"}	t        j                  d|	        Y d }	~	y d }	~	ww xY w)Nr   r   z#temperature_2m,relative_humidity_2mr!   r"   r)   r'   r+   r,   r-   r.   r    relative_humidity_2m)r.   r    rL         r/   )r#   r$   r   r0   r1   r2   r3   r4   r5   r6   r7   r8   rC   hourr9   )
r:   rH   r#   r$   r;   r*   r<   r=   r>   r?   s
             r   obter_dados_dia_mais_quenterP   N   sU   H!!I
9C%..z:#,,Z87'F<<F3!!#}}4MMKH:UWXaWbbcde\\N6*"8n-=>$(N3I$J
 
 ^^BvJ/6
F##q(RZ]]-?-?2-EFG	 4QC89s    AD BD 	E
(EE
c                 (   | j                   j                  rI| j                   j                  r3t        j                  | j                   j                  j
                         t        t        |      }|j                  r|j                  st        | dddi      S t               \  }}t        |||      }||j                  rt        | dddi      S t        |      \  }}t        j                   j#                  ||      }|j%                         r|j'                  ddd	d
      }	n]t)        ||      }
|
|
j                  rt        | dddi      S |
j+                  d d      |
d
<   t-        ||
       |
j/                  d      }	t        | d||||	||d      S )Nidzprojeto/erro.htmlerrou3   As coordenadas do projeto não estão disponíveis.u)   Não foi possível obter as temperaturas.r:   r=   horar   r   r   u5   Não foi possível obter os dados do dia mais quente.c                 &    t        | d   | d         S Nr    rL   r   rows    r   <lambda>z,obter_temperaturas_projeto.<locals>.<lambda>   s    1#6F2GMcIde r   r   axisrecordszcondicaoext/temperaturas.html)r:   rH   rI   temperaturas_horariasperiodo_inicioperiodo_fim)useris_authenticatedtenantr
   
set_schemaschema_namer   r   r#   r$   r   r   r@   emptyrJ   r	   objectsfilterexistsvaluesrP   applysalvar_dados_climaticosto_dict)request
projeto_idr:   r   r   df_temperaturasrH   rI   dados_existentesr`   df_dia_mais_quentes              r   obter_temperaturas_projetoru   r   s   ||$$)<)<gll11==>J7G7#4#4g2V=r4stt 9:K0+xPO/"7"7g2V=h4ijj'B?'S$O_ #**11'1X  0 7 7Oacu v8/R%);)A)A'#6Ax8yzz1C1I1Ielm 2J 2
-.
 	 );< 2 : :9 E':**!6%=  r   c                    t        t        |       }t               \  }}t        |||      }||j                  rt        d       y t        |      \  }}t        j                  j                  ||      }|j                         rt        d       y t        ||      }||j                  rt        d       y |j                  d d      |d	<   t        ||       t        d
| d       y )NrR   u/   Erro: Não foi possível obter as temperaturas.rU   uP   As temperaturas para o dia mais quente já estão registradas no banco de dados.u;   Erro: Não foi possível obter os dados do dia mais quente.c                 &    t        | d   | d         S rX   rY   rZ   s    r   r\   z8registrar_temperaturas_dia_mais_quente.<locals>.<lambda>   s    -c2B.CSI_E`a r   r   r]   r   z!Temperaturas do dia mais quente (z) registradas com sucesso.)r   r   r   r@   rh   printrJ   r	   ri   rj   rk   rP   rm   rn   )	rq   r:   r   r   rr   rH   rI   rs   rt   s	            r   &registrar_temperaturas_dia_mais_quentery      s    J7G 9:K 1+xPO/"7"7?@ (C?'S$O_ #**11'1X `a 5WoN!%7%=%=KL .@-E-Eahi .F .)*
 G%78	-o->>X
YZr   )settingsc                 <   |d   j                  t              |d<   |j                         D ]Y  \  }}t        j                  j                  | |d   j                         |d   j                         |d   |d   |d   |d          [ t        j                  j                  t        j                  d| j                         }t        j                  |d	       t        j                  j                  |d
| j                   d      }|j                  |ddd       y )Nr    calor_latenter.   rL   r   )r:   r=   rV   r   r   r   r|   z1/var/www/html/cagpublico/cag/arquivos_climaticos/Texist_okdados_climaticos_.csvF;utf-8indexsepencoding)rm   calcular_calor_latenteiterrowsr	   ri   createrB   r.   ospathjoinrz   
MEDIA_ROOTnome_projetomakedirsto_csv)r:   rt   _r[   caminho_pasta_projetocaminho_csvs         r   rn   rn      s.   *<=M*N*T*TUk*l' %--/ 	
3""V!!#V!!#,- !78 !34o. 	# 	
	
 GGLL)<)<@qry  sG  sG  rH  ?I  J KK%5 '',,48I'J^J^I__c6deK kC'Rr   )
DateFormatc                     t        j                         }|j                  t        j                  | |d             |j	                  |||d       t        j                  |d      S )Nzlines+markers)xymodeplotly_white)titlexaxis_titleyaxis_titletemplateF	full_html)goFigure	add_traceScatterupdate_layoutpioto_html)r   r   tituloxlabelylabelfigs         r   gerar_grafico_plotlyr      sZ    
))+CMM"**qAO<= 	   ;;se,,r   r   c                      t        | dddi      S )Ncondicaoext/erro.htmlmensagemu.   Página não encontrada ou outro erro ocorreu.r   )rp   s    r   exibir_error     s    '2ZAq4rssr   c                 :    dd| z  z
  d| dz  z  z   d| dz  z  z
  }|S )Ng@gzG@g-C6Z?   giUMu?    )tempLs     r   r   r     s1    va//'D!G2CCAHr   )Ambiente)DadosTermicos)r   c                 	   | j                   j                  rI| j                   j                  r3t        j                  | j                   j                  j
                         t        t        |      }t        j                  j                  |      }|j                         st        | dddi      S |j                         }t        j                  j                  |      j                         }|st        | dddi      S t        j                   j#                  t$        j&                  d|j(                   d	|j(                   d
      }t        j                   j                  |      st        | dddi      S t+        j,                  |dd      }t+        j.                  |d         |d<   |j0                  }t3        |      }	t+        j4                  |d   |	gt7        |d         z  d      }
t9        j:                         }|j=                  t9        j>                  |
d   |
d   dd| d             |jA                  d| dddtC        d      dd       |jE                  d       }|d!   jG                  t2              |d"<   t9        j:                         }|j=                  t9        j>                  |d   |d"   dd#             |jA                  d$ddtC        d      dd       |jE                  d       }t9        j:                         }|j=                  t9        j>                  |d   |d!   dd%             |jA                  d&dd%tC        d      dd       |jE                  d       }t9        j:                         }|j=                  t9        j>                  |d   |d'   dd(             |jA                  d)dd(tC        d      dd       |jE                  d       }t9        j:                         }|j=                  t9        j>                  |d   |d*   dd+             |jA                  d,dd+tC        d      dd       |jE                  d       }|d   jH                  d-   }tK        |t*        jL                        r|jO                         }n|}|d!   jQ                         }t        | d.|||||||||d/	      S )0NrR   )r:   r   r   z-Nenhum ambiente encontrado para este projeto.)ambienteu0   Nenhum dado térmico encontrado para o ambiente.arquivos_climaticos/z/dados_climaticos_r   u"   Nenhum dado climático encontrado.r   r   )r   r   r.   )r.   calor_latente_internar   lineszCalor Latente Interno (u   °C))r   r   r   namez*Calor Latente para Temperatura Interna de u   °Cu   HoráriozCalor Latente (kJ/kg)i6 )dticki  iX  )r   r   r   xaxiswidthheightFr   r    calor_latente_diazCalor Latente Externo (kJ/kg)z-Calor Latente Externo ao Longo do Dia (kJ/kg)u   Temperatura (°C)u"   Temperatura Externa Horária (°C)rL   zUmidade Relativa (%)u   Umidade Relativa Horária (%)r   zUmidade Absoluta (g/kg)u    Umidade Absoluta Horária (g/kg)r   zcondicaoext/registrocsv.html)	r:   rH   rI   	plot_tempplot_umidade_relplot_umidade_absplot_calor_latente_diaplot_calor_latente_internatemperatura_interna))rc   rd   re   r
   rf   rg   r   r   r   ri   rj   rk   r   firstr   r   r   r   rz   r   r   r6   read_csvr8   r   r   r7   lenr   r   r   r   r   dictr   rm   iloc
isinstance	Timestampto_pydatetimerE   )rp   rq   r:   	ambientesr   dados_termicosr   r>   r   r   df_calor_latente_internafig_calor_latente_internar   fig_calor_latente_diar   fig_tempr   fig_umidade_relr   fig_umidade_absr   dia_mais_quente_pandasrH   rI   s                           r   exibir_graficos_csvr   A  s    ||$$)<)<gll11==>  J7G   '''8Ig6Et8uvv  H #**1181DJJLNg6Ew8xyy '',,
w3344FwG[G[F\\`aK 77>>+&g6Ei8jkk 
[cG	<B 6
+BvJ )<< 33FG  "||6
"7!83r&z?!J-   !#		''


"6
*
"#:
;&':&;4@	)  ++:;N:OsS+! ,  ";!B!BU!B!S !!12889OPBIIK##BJJ
V*
 
!,	%  ''=+! (  3::U:K yy{Hrzz
V*

 	  2'!     5 1I iikObjj
V*
#
$#	  !!-*! "  '...? iikObjj
V*

 &	  !!0-! "  '...?  Z__Q/(",,70>>@0 )*..0O '9**,,"8&@2
< 
 
r   c                 j   t        j                  |d         |d<   t        j                         }| j                  gt	        |      z  |d<   |d   j
                  j                  |d<   |d   j
                  j                  d      |d<   |d   |d<   t        j                  j                  t        j                  d| j                         }t        j                  |d	
       t        j                  j                  |d| j                   d      }|j                  |ddd       t        d|        y)u   
    Grava em CSV as colunas solicitadas: 'cidade', 'data', 'hora', 'temperatura'.
    Assim é possível avaliar se as informações retornadas pela API estão corretas.
    r.   cidader=   z%H:%MrV   r    r   r   Tr}   historico_api_r   Fr   r   r   zArquivo CSV gerado em: N)r6   r8   r7   r   r   rC   rB   r   r   r   r   rz   r   r   r   rx   )r:   rr   	df_exportpasta_saidar   s        r   gravar_csv_temperaturasr     s*    !nn_V-DEOF I"//033GGIh'/2277If'/22;;GDIf./?@Im '',,
w3345K KKd+'',,
--.d3K 	   
#K=
12r   c                    | j                   j                  rI| j                   j                  r3t        j                  | j                   j                  j
                         t        t        |      }t               \  }}t        |||      }||j                  rt        | dddi      S t        ||       t        | dddi      S )NrR   r   r   uL   Não foi possível obter as temperaturas ou nenhuma temperatura disponível.zcondicaoext/sucesso.htmlz+CSV gerado com sucesso e salvo no servidor!)rc   rd   re   r
   rf   rg   r   r   r   r@   rh   r   r   )rp   rq   r:   r   r   rr   s         r   salvar_temperaturas_csvr     s     ||$$)<)<gll11==>  J7G 9:K 1+xPO /"7"7#gh
 	
 G_5 "	BC r   )2django.shortcutsr   r   r   r   projeto.modelsr   modelsr	   r   r0   pandasr6   r4   	django.dbr
   django.contrib.auth.decoratorsr   r   r   r@   rJ   rP   ru   ry   r   django.confrz   rn   plotly.graph_objs
graph_objsr   	plotly.ioior   django.utils.dateformatr   r   r   plotly.graph_objectsgraph_objectsr   ctermica.modelsr   termicos.modelsr   viewsr   r   r   r   r   r   <module>r      sn   6 ( "        9 6 ( "        9KD,!H , ,b$[P 
  
S< 
    6 "   .-  $t 
    6 ! " 
  ! 6  $ )   9 6 9   	    ! 9 6     	  ! " $ )  )` `L 
   #3J 7 9     	   r   