entropy25 commited on
Commit
bb615b4
·
verified ·
1 Parent(s): 6d117a0

Update utils.py

Browse files
Files changed (1) hide show
  1. utils.py +34 -66
utils.py CHANGED
@@ -17,37 +17,25 @@ def init_session_state():
17
  if 'csv_data' not in st.session_state:
18
  st.session_state.csv_data = None
19
 
20
- def init_session_state():
21
- if 'current_df' not in st.session_state:
22
- st.session_state.current_df = None
23
- if 'current_stats' not in st.session_state:
24
- st.session_state.current_stats = None
25
- if 'export_ready' not in st.session_state:
26
- st.session_state.export_ready = False
27
- if 'pdf_buffer' not in st.session_state:
28
- st.session_state.pdf_buffer = None
29
- if 'csv_data' not in st.session_state:
30
- st.session_state.csv_data = None
31
-
32
- def render_export_section(df: pd.DataFrame, stats: Dict, outliers: Dict, model):
33
- st.markdown('<div class="section-header">Export Reports</div>', unsafe_allow_html=True)
34
 
35
  col1, col2, col3 = st.columns(3)
36
 
37
  with col1:
38
- if st.button("Generate PDF Report", key="generate_pdf_btn", type="primary"):
39
  try:
40
- with st.spinner("Generating comprehensive PDF report..."):
41
  st.session_state.pdf_buffer = create_enhanced_pdf_report(df, stats, outliers, model)
42
  st.session_state.export_ready = True
43
- st.success("PDF report generated successfully")
44
  except Exception as e:
45
- st.error(f"PDF generation failed: {str(e)}")
46
  st.session_state.export_ready = False
47
 
48
  if st.session_state.export_ready and st.session_state.pdf_buffer:
49
  st.download_button(
50
- label="Download PDF Report",
51
  data=st.session_state.pdf_buffer,
52
  file_name=f"production_report_{datetime.now().strftime('%Y%m%d_%H%M')}.pdf",
53
  mime="application/pdf",
@@ -55,17 +43,17 @@ def render_export_section(df: pd.DataFrame, stats: Dict, outliers: Dict, model):
55
  )
56
 
57
  with col2:
58
- if st.button("Generate CSV Summary", key="generate_csv_btn", type="primary"):
59
  try:
60
  st.session_state.csv_data = create_csv_export(df, stats)
61
- st.success("CSV summary generated successfully")
62
  except Exception as e:
63
- st.error(f"CSV generation failed: {str(e)}")
64
 
65
  if st.session_state.csv_data is not None:
66
  csv_string = st.session_state.csv_data.to_csv(index=False)
67
  st.download_button(
68
- label="Download CSV Summary",
69
  data=csv_string,
70
  file_name=f"production_summary_{datetime.now().strftime('%Y%m%d_%H%M')}.csv",
71
  mime="text/csv",
@@ -75,15 +63,15 @@ def render_export_section(df: pd.DataFrame, stats: Dict, outliers: Dict, model):
75
  with col3:
76
  csv_string = df.to_csv(index=False)
77
  st.download_button(
78
- label="Download Raw Data",
79
  data=csv_string,
80
  file_name=f"raw_production_data_{datetime.now().strftime('%Y%m%d_%H%M')}.csv",
81
  mime="text/csv",
82
  key="download_raw_btn"
83
  )
84
 
85
- def render_quality_check(outliers: Dict):
86
- st.markdown('<div class="section-header">Quality Check</div>', unsafe_allow_html=True)
87
 
88
  cols = st.columns(len(outliers))
89
  for i, (material, info) in enumerate(outliers.items()):
@@ -92,72 +80,52 @@ def render_quality_check(outliers: Dict):
92
  dates_str = ", ".join(info['dates'])
93
  st.markdown(f'''<div class="alert-warning">
94
  <strong>{material.title()}</strong><br>
95
- {info["count"]} outliers detected<br>
96
- Normal range: {info["range"]}<br>
97
  <div class="quality-dates">Dates: {dates_str}</div>
98
  </div>''', unsafe_allow_html=True)
99
  else:
100
- st.markdown(f'<div class="alert-success"><strong>{material.title()}</strong><br>All values normal</div>',
101
  unsafe_allow_html=True)
102
 
103
- def render_ai_insights(model, stats: Dict, df: pd.DataFrame):
104
- st.markdown('<div class="section-header">AI Insights</div>', unsafe_allow_html=True)
105
 
106
- quick_questions = [
107
- "How does production distribution on weekdays compare to weekends?",
108
- "Which material exhibits the most volatility in our dataset?",
109
- "To improve stability, which material or shift needs immediate attention?"
110
- ]
111
 
112
  cols = st.columns(len(quick_questions))
113
  for i, q in enumerate(quick_questions):
114
  with cols[i]:
115
  if st.button(q, key=f"ai_q_{i}"):
116
  from ai_engine import query_ai
117
- with st.spinner("Analyzing..."):
118
- answer = query_ai(model, stats, q, df)
119
  st.info(answer)
120
 
121
  custom_question = st.text_input(
122
- "Ask about your production data:",
123
- placeholder="e.g., 'Compare steel vs aluminum last month'",
124
  key="custom_ai_question"
125
  )
126
 
127
- if custom_question and st.button("Ask AI", key="ask_ai_btn"):
128
  from ai_engine import query_ai
129
- with st.spinner("Analyzing..."):
130
- answer = query_ai(model, stats, custom_question, df)
131
  st.success(f"**Q:** {custom_question}")
132
  st.write(f"**A:** {answer}")
133
 
134
- def render_welcome_screen():
135
- st.markdown('<div class="section-header">How to Use This Platform</div>', unsafe_allow_html=True)
136
 
137
  col1, col2 = st.columns(2)
138
 
139
  with col1:
140
- st.markdown("""
141
- ### Quick Start
142
- 1. Upload your TSV data in the sidebar
143
- 2. Or click Quick Load buttons for preset data
144
- 3. View production by material type
145
- 4. Analyze trends (daily/weekly/monthly)
146
- 5. Check anomalies in Quality Check
147
- 6. Export reports (PDF with AI, CSV)
148
- 7. Ask the AI assistant for insights
149
- """)
150
 
151
  with col2:
152
- st.markdown("""
153
- ### Key Features
154
- - Real-time interactive charts
155
- - One-click preset data loading
156
- - Time-period comparisons
157
- - Shift performance analysis
158
- - Outlier detection with dates
159
- - AI-powered PDF reports
160
- - Intelligent recommendations
161
- """)
162
 
163
- st.info("Ready to start? Upload your production data or use Quick Load buttons to begin analysis")
 
17
  if 'csv_data' not in st.session_state:
18
  st.session_state.csv_data = None
19
 
20
+ def render_export_section(df: pd.DataFrame, stats: Dict, outliers: Dict, model, t: Dict):
21
+ st.markdown(f'<div class="section-header">{t["section_export"]}</div>', unsafe_allow_html=True)
 
 
 
 
 
 
 
 
 
 
 
 
22
 
23
  col1, col2, col3 = st.columns(3)
24
 
25
  with col1:
26
+ if st.button(t['btn_generate_pdf'], key="generate_pdf_btn", type="primary"):
27
  try:
28
+ with st.spinner(t['pdf_generating']):
29
  st.session_state.pdf_buffer = create_enhanced_pdf_report(df, stats, outliers, model)
30
  st.session_state.export_ready = True
31
+ st.success(t['pdf_success'])
32
  except Exception as e:
33
+ st.error(f"{t['pdf_failed']}: {str(e)}")
34
  st.session_state.export_ready = False
35
 
36
  if st.session_state.export_ready and st.session_state.pdf_buffer:
37
  st.download_button(
38
+ label=t['btn_download_pdf'],
39
  data=st.session_state.pdf_buffer,
40
  file_name=f"production_report_{datetime.now().strftime('%Y%m%d_%H%M')}.pdf",
41
  mime="application/pdf",
 
43
  )
44
 
45
  with col2:
46
+ if st.button(t['btn_generate_csv'], key="generate_csv_btn", type="primary"):
47
  try:
48
  st.session_state.csv_data = create_csv_export(df, stats)
49
+ st.success(t['csv_success'])
50
  except Exception as e:
51
+ st.error(f"{t['csv_failed']}: {str(e)}")
52
 
53
  if st.session_state.csv_data is not None:
54
  csv_string = st.session_state.csv_data.to_csv(index=False)
55
  st.download_button(
56
+ label=t['btn_download_csv'],
57
  data=csv_string,
58
  file_name=f"production_summary_{datetime.now().strftime('%Y%m%d_%H%M')}.csv",
59
  mime="text/csv",
 
63
  with col3:
64
  csv_string = df.to_csv(index=False)
65
  st.download_button(
66
+ label=t['btn_download_raw'],
67
  data=csv_string,
68
  file_name=f"raw_production_data_{datetime.now().strftime('%Y%m%d_%H%M')}.csv",
69
  mime="text/csv",
70
  key="download_raw_btn"
71
  )
72
 
73
+ def render_quality_check(outliers: Dict, t: Dict):
74
+ st.markdown(f'<div class="section-header">{t["section_quality_check"]}</div>', unsafe_allow_html=True)
75
 
76
  cols = st.columns(len(outliers))
77
  for i, (material, info) in enumerate(outliers.items()):
 
80
  dates_str = ", ".join(info['dates'])
81
  st.markdown(f'''<div class="alert-warning">
82
  <strong>{material.title()}</strong><br>
83
+ {info["count"]} {t['quality_outliers']}<br>
84
+ {t['quality_normal_range']}: {info["range"]}<br>
85
  <div class="quality-dates">Dates: {dates_str}</div>
86
  </div>''', unsafe_allow_html=True)
87
  else:
88
+ st.markdown(f'<div class="alert-success"><strong>{material.title()}</strong><br>{t["quality_normal"]}</div>',
89
  unsafe_allow_html=True)
90
 
91
+ def render_ai_insights(model, stats: Dict, df: pd.DataFrame, t: Dict, lang: str):
92
+ st.markdown(f'<div class="section-header">{t["section_ai_insights"]}</div>', unsafe_allow_html=True)
93
 
94
+ quick_questions = [t['ai_quick_q1'], t['ai_quick_q2'], t['ai_quick_q3']]
 
 
 
 
95
 
96
  cols = st.columns(len(quick_questions))
97
  for i, q in enumerate(quick_questions):
98
  with cols[i]:
99
  if st.button(q, key=f"ai_q_{i}"):
100
  from ai_engine import query_ai
101
+ with st.spinner(t['ai_analyzing']):
102
+ answer = query_ai(model, stats, q, df, lang)
103
  st.info(answer)
104
 
105
  custom_question = st.text_input(
106
+ t['ai_ask_label'],
107
+ placeholder=t['ai_custom_placeholder'],
108
  key="custom_ai_question"
109
  )
110
 
111
+ if custom_question and st.button(t['ai_ask_btn'], key="ask_ai_btn"):
112
  from ai_engine import query_ai
113
+ with st.spinner(t['ai_analyzing']):
114
+ answer = query_ai(model, stats, custom_question, df, lang)
115
  st.success(f"**Q:** {custom_question}")
116
  st.write(f"**A:** {answer}")
117
 
118
+ def render_welcome_screen(t: Dict):
119
+ st.markdown(f'<div class="section-header">{t["welcome_title"]}</div>', unsafe_allow_html=True)
120
 
121
  col1, col2 = st.columns(2)
122
 
123
  with col1:
124
+ st.markdown(f"### {t['welcome_quick_start']}")
125
+ st.markdown(t['welcome_steps'])
 
 
 
 
 
 
 
 
126
 
127
  with col2:
128
+ st.markdown(f"### {t['welcome_features']}")
129
+ st.markdown(t['welcome_features_list'])
 
 
 
 
 
 
 
 
130
 
131
+ st.info(t['welcome_ready'])