entropy25's picture
Update utils.py
bb615b4 verified
import streamlit as st
from datetime import datetime
from typing import Dict
import pandas as pd
from pdf_generator import create_enhanced_pdf_report, create_csv_export
def init_session_state():
if 'current_df' not in st.session_state:
st.session_state.current_df = None
if 'current_stats' not in st.session_state:
st.session_state.current_stats = None
if 'export_ready' not in st.session_state:
st.session_state.export_ready = False
if 'pdf_buffer' not in st.session_state:
st.session_state.pdf_buffer = None
if 'csv_data' not in st.session_state:
st.session_state.csv_data = None
def render_export_section(df: pd.DataFrame, stats: Dict, outliers: Dict, model, t: Dict):
st.markdown(f'<div class="section-header">{t["section_export"]}</div>', unsafe_allow_html=True)
col1, col2, col3 = st.columns(3)
with col1:
if st.button(t['btn_generate_pdf'], key="generate_pdf_btn", type="primary"):
try:
with st.spinner(t['pdf_generating']):
st.session_state.pdf_buffer = create_enhanced_pdf_report(df, stats, outliers, model)
st.session_state.export_ready = True
st.success(t['pdf_success'])
except Exception as e:
st.error(f"{t['pdf_failed']}: {str(e)}")
st.session_state.export_ready = False
if st.session_state.export_ready and st.session_state.pdf_buffer:
st.download_button(
label=t['btn_download_pdf'],
data=st.session_state.pdf_buffer,
file_name=f"production_report_{datetime.now().strftime('%Y%m%d_%H%M')}.pdf",
mime="application/pdf",
key="download_pdf_btn"
)
with col2:
if st.button(t['btn_generate_csv'], key="generate_csv_btn", type="primary"):
try:
st.session_state.csv_data = create_csv_export(df, stats)
st.success(t['csv_success'])
except Exception as e:
st.error(f"{t['csv_failed']}: {str(e)}")
if st.session_state.csv_data is not None:
csv_string = st.session_state.csv_data.to_csv(index=False)
st.download_button(
label=t['btn_download_csv'],
data=csv_string,
file_name=f"production_summary_{datetime.now().strftime('%Y%m%d_%H%M')}.csv",
mime="text/csv",
key="download_csv_btn"
)
with col3:
csv_string = df.to_csv(index=False)
st.download_button(
label=t['btn_download_raw'],
data=csv_string,
file_name=f"raw_production_data_{datetime.now().strftime('%Y%m%d_%H%M')}.csv",
mime="text/csv",
key="download_raw_btn"
)
def render_quality_check(outliers: Dict, t: Dict):
st.markdown(f'<div class="section-header">{t["section_quality_check"]}</div>', unsafe_allow_html=True)
cols = st.columns(len(outliers))
for i, (material, info) in enumerate(outliers.items()):
with cols[i]:
if info['count'] > 0:
dates_str = ", ".join(info['dates'])
st.markdown(f'''<div class="alert-warning">
<strong>{material.title()}</strong><br>
{info["count"]} {t['quality_outliers']}<br>
{t['quality_normal_range']}: {info["range"]}<br>
<div class="quality-dates">Dates: {dates_str}</div>
</div>''', unsafe_allow_html=True)
else:
st.markdown(f'<div class="alert-success"><strong>{material.title()}</strong><br>{t["quality_normal"]}</div>',
unsafe_allow_html=True)
def render_ai_insights(model, stats: Dict, df: pd.DataFrame, t: Dict, lang: str):
st.markdown(f'<div class="section-header">{t["section_ai_insights"]}</div>', unsafe_allow_html=True)
quick_questions = [t['ai_quick_q1'], t['ai_quick_q2'], t['ai_quick_q3']]
cols = st.columns(len(quick_questions))
for i, q in enumerate(quick_questions):
with cols[i]:
if st.button(q, key=f"ai_q_{i}"):
from ai_engine import query_ai
with st.spinner(t['ai_analyzing']):
answer = query_ai(model, stats, q, df, lang)
st.info(answer)
custom_question = st.text_input(
t['ai_ask_label'],
placeholder=t['ai_custom_placeholder'],
key="custom_ai_question"
)
if custom_question and st.button(t['ai_ask_btn'], key="ask_ai_btn"):
from ai_engine import query_ai
with st.spinner(t['ai_analyzing']):
answer = query_ai(model, stats, custom_question, df, lang)
st.success(f"**Q:** {custom_question}")
st.write(f"**A:** {answer}")
def render_welcome_screen(t: Dict):
st.markdown(f'<div class="section-header">{t["welcome_title"]}</div>', unsafe_allow_html=True)
col1, col2 = st.columns(2)
with col1:
st.markdown(f"### {t['welcome_quick_start']}")
st.markdown(t['welcome_steps'])
with col2:
st.markdown(f"### {t['welcome_features']}")
st.markdown(t['welcome_features_list'])
st.info(t['welcome_ready'])