Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -17,7 +17,6 @@ import tempfile
|
|
| 17 |
import os
|
| 18 |
import requests
|
| 19 |
|
| 20 |
-
# Design System Configuration
|
| 21 |
DESIGN_SYSTEM = {
|
| 22 |
'colors': {
|
| 23 |
'primary': '#1E40AF',
|
|
@@ -36,7 +35,6 @@ DESIGN_SYSTEM = {
|
|
| 36 |
}
|
| 37 |
}
|
| 38 |
|
| 39 |
-
# Page config
|
| 40 |
st.set_page_config(
|
| 41 |
page_title="Production Monitor | Nilsen Service & Consulting",
|
| 42 |
page_icon="π",
|
|
@@ -44,7 +42,6 @@ st.set_page_config(
|
|
| 44 |
initial_sidebar_state="expanded"
|
| 45 |
)
|
| 46 |
|
| 47 |
-
# Custom CSS
|
| 48 |
def load_css():
|
| 49 |
st.markdown(f"""
|
| 50 |
<style>
|
|
@@ -137,8 +134,6 @@ def init_ai():
|
|
| 137 |
|
| 138 |
@st.cache_data
|
| 139 |
def load_preset_data(year):
|
| 140 |
-
"""Load preset data from remote source"""
|
| 141 |
-
# Note: Replace with actual URLs to your hosted datasets
|
| 142 |
urls = {
|
| 143 |
"2024": "https://huggingface.co/spaces/entropy25/production-data-analysis/resolve/main/2024.csv",
|
| 144 |
"2025": "https://huggingface.co/spaces/entropy25/production-data-analysis/resolve/main/2025.csv"
|
|
@@ -160,7 +155,6 @@ def load_preset_data(year):
|
|
| 160 |
return generate_sample_data(year)
|
| 161 |
|
| 162 |
def generate_sample_data(year):
|
| 163 |
-
"""Generate sample production data for demonstration"""
|
| 164 |
np.random.seed(42 if year == "2024" else 84)
|
| 165 |
|
| 166 |
start_date = f"01/01/{year}"
|
|
@@ -358,15 +352,12 @@ def detect_outliers(df):
|
|
| 358 |
return outliers
|
| 359 |
|
| 360 |
def generate_ai_summary(model, df, stats, outliers):
|
| 361 |
-
"""Generate comprehensive AI analysis for PDF report"""
|
| 362 |
if not model:
|
| 363 |
return "AI analysis unavailable - API key not configured"
|
| 364 |
|
| 365 |
try:
|
| 366 |
-
# Prepare data context
|
| 367 |
materials = [k for k in stats.keys() if k != '_total_']
|
| 368 |
|
| 369 |
-
# Build context for AI
|
| 370 |
context_parts = [
|
| 371 |
"# Production Data Analysis Context",
|
| 372 |
f"## Overview",
|
|
@@ -382,7 +373,6 @@ def generate_ai_summary(model, df, stats, outliers):
|
|
| 382 |
info = stats[material]
|
| 383 |
context_parts.append(f"- {material.title()}: {info['total']:,.0f} kg ({info['percentage']:.1f}%), avg {info['daily_avg']:,.0f} kg/day")
|
| 384 |
|
| 385 |
-
# Add trend analysis
|
| 386 |
daily_data = df.groupby('date')['weight_kg'].sum()
|
| 387 |
trend_direction = "increasing" if daily_data.iloc[-1] > daily_data.iloc[0] else "decreasing"
|
| 388 |
volatility = daily_data.std() / daily_data.mean() * 100
|
|
@@ -396,7 +386,6 @@ def generate_ai_summary(model, df, stats, outliers):
|
|
| 396 |
f"- Lowest production: {daily_data.min():,.0f} kg"
|
| 397 |
])
|
| 398 |
|
| 399 |
-
# Add quality information
|
| 400 |
total_outliers = sum(info['count'] for info in outliers.values())
|
| 401 |
context_parts.extend([
|
| 402 |
"",
|
|
@@ -405,7 +394,6 @@ def generate_ai_summary(model, df, stats, outliers):
|
|
| 405 |
f"- Materials with quality issues: {sum(1 for info in outliers.values() if info['count'] > 0)}"
|
| 406 |
])
|
| 407 |
|
| 408 |
-
# Add shift analysis if available
|
| 409 |
if 'shift' in df.columns:
|
| 410 |
shift_stats = df.groupby('shift')['weight_kg'].sum()
|
| 411 |
context_parts.extend([
|
|
@@ -417,7 +405,6 @@ def generate_ai_summary(model, df, stats, outliers):
|
|
| 417 |
|
| 418 |
context_text = "\n".join(context_parts)
|
| 419 |
|
| 420 |
-
# AI analysis prompt
|
| 421 |
prompt = f"""
|
| 422 |
{context_text}
|
| 423 |
|
|
@@ -449,7 +436,6 @@ Keep the analysis professional, data-driven, and under 300 words. Focus on actio
|
|
| 449 |
return f"AI analysis error: {str(e)}"
|
| 450 |
|
| 451 |
def query_ai(model, stats, question, df=None):
|
| 452 |
-
"""AI assistant for interactive queries"""
|
| 453 |
if not model:
|
| 454 |
return "AI assistant not available"
|
| 455 |
|
|
@@ -481,19 +467,21 @@ def query_ai(model, stats, question, df=None):
|
|
| 481 |
return "Error getting AI response"
|
| 482 |
|
| 483 |
def save_plotly_as_image(fig, filename):
|
| 484 |
-
"""Convert Plotly figure to PNG for PDF"""
|
| 485 |
try:
|
| 486 |
temp_dir = tempfile.gettempdir()
|
| 487 |
filepath = os.path.join(temp_dir, filename)
|
| 488 |
|
| 489 |
-
|
| 490 |
-
|
| 491 |
-
|
| 492 |
-
|
| 493 |
-
|
| 494 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 495 |
|
| 496 |
-
# Try to save the image, if fails, return None silently
|
| 497 |
try:
|
| 498 |
pio.write_image(fig, filepath, format='png', width=800, height=400, scale=2, engine='kaleido')
|
| 499 |
if os.path.exists(filepath):
|
|
@@ -507,7 +495,6 @@ def save_plotly_as_image(fig, filename):
|
|
| 507 |
return None
|
| 508 |
|
| 509 |
def create_pdf_charts(df, stats):
|
| 510 |
-
"""Generate charts for PDF report"""
|
| 511 |
charts = {}
|
| 512 |
|
| 513 |
try:
|
|
@@ -555,14 +542,12 @@ def create_pdf_charts(df, stats):
|
|
| 555 |
return charts
|
| 556 |
|
| 557 |
def create_enhanced_pdf_report(df, stats, outliers, model=None):
|
| 558 |
-
"""Generate comprehensive PDF report with AI analysis"""
|
| 559 |
buffer = io.BytesIO()
|
| 560 |
doc = SimpleDocTemplate(buffer, pagesize=A4, rightMargin=50, leftMargin=50, topMargin=50, bottomMargin=50)
|
| 561 |
|
| 562 |
elements = []
|
| 563 |
styles = getSampleStyleSheet()
|
| 564 |
|
| 565 |
-
# Custom styles
|
| 566 |
title_style = ParagraphStyle(
|
| 567 |
'CustomTitle',
|
| 568 |
parent=styles['Heading1'],
|
|
@@ -589,13 +574,11 @@ def create_enhanced_pdf_report(df, stats, outliers, model=None):
|
|
| 589 |
textColor=colors.darkgreen
|
| 590 |
)
|
| 591 |
|
| 592 |
-
# Cover page
|
| 593 |
elements.append(Spacer(1, 100))
|
| 594 |
elements.append(Paragraph("Production Monitor Report", title_style))
|
| 595 |
elements.append(Paragraph("Comprehensive Production Analysis with AI Insights", styles['Heading3']))
|
| 596 |
elements.append(Spacer(1, 50))
|
| 597 |
|
| 598 |
-
# Report info
|
| 599 |
report_info = f"""
|
| 600 |
<para alignment="center">
|
| 601 |
<b>Nilsen Service & Consulting AS</b><br/>
|
|
@@ -608,7 +591,6 @@ def create_enhanced_pdf_report(df, stats, outliers, model=None):
|
|
| 608 |
elements.append(Paragraph(report_info, styles['Normal']))
|
| 609 |
elements.append(PageBreak())
|
| 610 |
|
| 611 |
-
# Executive Summary
|
| 612 |
elements.append(Paragraph("Executive Summary", subtitle_style))
|
| 613 |
|
| 614 |
total_production = stats['_total_']['total']
|
|
@@ -631,7 +613,6 @@ def create_enhanced_pdf_report(df, stats, outliers, model=None):
|
|
| 631 |
elements.append(Paragraph(exec_summary, styles['Normal']))
|
| 632 |
elements.append(Spacer(1, 20))
|
| 633 |
|
| 634 |
-
# Production Summary Table
|
| 635 |
elements.append(Paragraph("Production Summary", styles['Heading3']))
|
| 636 |
|
| 637 |
summary_data = [['Material Type', 'Total (kg)', 'Share (%)', 'Daily Avg (kg)']]
|
|
@@ -658,7 +639,6 @@ def create_enhanced_pdf_report(df, stats, outliers, model=None):
|
|
| 658 |
elements.append(summary_table)
|
| 659 |
elements.append(PageBreak())
|
| 660 |
|
| 661 |
-
# Generate and add charts
|
| 662 |
elements.append(Paragraph("Production Analysis Charts", subtitle_style))
|
| 663 |
|
| 664 |
try:
|
|
@@ -668,7 +648,6 @@ def create_enhanced_pdf_report(df, stats, outliers, model=None):
|
|
| 668 |
|
| 669 |
charts_added = False
|
| 670 |
|
| 671 |
-
# Chart sections with Phase 2: AI insights for key charts
|
| 672 |
chart_insights = {
|
| 673 |
'pie': "Material distribution shows production allocation across different materials. Balanced distribution indicates diversified production capabilities.",
|
| 674 |
'trend': "Production trend reveals operational patterns and seasonal variations. Consistent trends suggest stable operational efficiency.",
|
|
@@ -688,7 +667,6 @@ def create_enhanced_pdf_report(df, stats, outliers, model=None):
|
|
| 688 |
elements.append(Paragraph(chart_title, styles['Heading3']))
|
| 689 |
elements.append(Image(chart_path, width=6*inch, height=3*inch))
|
| 690 |
|
| 691 |
-
# Phase 2: Add AI insight for this chart
|
| 692 |
insight_text = f"<i>Analysis: {chart_insights.get(chart_type, 'Chart analysis not available.')}</i>"
|
| 693 |
elements.append(Paragraph(insight_text, ai_style))
|
| 694 |
elements.append(Spacer(1, 20))
|
|
@@ -705,7 +683,6 @@ def create_enhanced_pdf_report(df, stats, outliers, model=None):
|
|
| 705 |
elements.append(Paragraph(summary_text, styles['Normal']))
|
| 706 |
elements.append(Spacer(1, 20))
|
| 707 |
|
| 708 |
-
# Quality Analysis
|
| 709 |
elements.append(PageBreak())
|
| 710 |
elements.append(Paragraph("Quality Control Analysis", subtitle_style))
|
| 711 |
|
|
@@ -738,7 +715,6 @@ def create_enhanced_pdf_report(df, stats, outliers, model=None):
|
|
| 738 |
|
| 739 |
elements.append(quality_table)
|
| 740 |
|
| 741 |
-
# Phase 1: AI Comprehensive Analysis Section
|
| 742 |
if model:
|
| 743 |
elements.append(PageBreak())
|
| 744 |
elements.append(Paragraph("AI Intelligent Analysis", subtitle_style))
|
|
@@ -748,13 +724,11 @@ def create_enhanced_pdf_report(df, stats, outliers, model=None):
|
|
| 748 |
except:
|
| 749 |
ai_analysis = "AI analysis temporarily unavailable."
|
| 750 |
|
| 751 |
-
# Format AI analysis with better styling
|
| 752 |
ai_paragraphs = ai_analysis.split('\n\n')
|
| 753 |
for paragraph in ai_paragraphs:
|
| 754 |
if paragraph.strip():
|
| 755 |
-
# Handle bold formatting
|
| 756 |
formatted_text = paragraph.replace('**', '<b>', 1).replace('**', '</b>', 1)
|
| 757 |
-
formatted_text = formatted_text.replace('β’', ' β’')
|
| 758 |
elements.append(Paragraph(formatted_text, styles['Normal']))
|
| 759 |
elements.append(Spacer(1, 8))
|
| 760 |
else:
|
|
@@ -762,7 +736,6 @@ def create_enhanced_pdf_report(df, stats, outliers, model=None):
|
|
| 762 |
elements.append(Paragraph("AI Analysis", subtitle_style))
|
| 763 |
elements.append(Paragraph("AI analysis unavailable - API key not configured. Please configure Google AI API key to enable intelligent insights.", styles['Normal']))
|
| 764 |
|
| 765 |
-
# Footer
|
| 766 |
elements.append(Spacer(1, 30))
|
| 767 |
footer_text = f"""
|
| 768 |
<para alignment="center">
|
|
@@ -778,7 +751,6 @@ def create_enhanced_pdf_report(df, stats, outliers, model=None):
|
|
| 778 |
return buffer
|
| 779 |
|
| 780 |
def create_csv_export(df, stats):
|
| 781 |
-
"""Create CSV export of summary data"""
|
| 782 |
summary_df = pd.DataFrame([
|
| 783 |
{
|
| 784 |
'Material': material.replace('_', ' ').title(),
|
|
@@ -793,7 +765,6 @@ def create_csv_export(df, stats):
|
|
| 793 |
|
| 794 |
return summary_df
|
| 795 |
|
| 796 |
-
|
| 797 |
def add_export_section(df, stats, outliers, model):
|
| 798 |
st.markdown('<div class="section-header">π Export Reports</div>', unsafe_allow_html=True)
|
| 799 |
|
|
@@ -862,10 +833,10 @@ def add_export_section(df, stats, outliers, model):
|
|
| 862 |
st.session_state.pdf_buffer = None
|
| 863 |
st.session_state.csv_data = None
|
| 864 |
st.rerun()
|
|
|
|
| 865 |
def main():
|
| 866 |
load_css()
|
| 867 |
|
| 868 |
-
# Header
|
| 869 |
st.markdown("""
|
| 870 |
<div class="main-header">
|
| 871 |
<div class="main-title">π Production Monitor</div>
|
|
@@ -880,17 +851,14 @@ def main():
|
|
| 880 |
if 'current_stats' not in st.session_state:
|
| 881 |
st.session_state.current_stats = None
|
| 882 |
|
| 883 |
-
# Sidebar
|
| 884 |
with st.sidebar:
|
| 885 |
st.markdown("### π Data Source")
|
| 886 |
|
| 887 |
-
# File upload option
|
| 888 |
uploaded_file = st.file_uploader("Upload Production Data", type=['csv'])
|
| 889 |
|
| 890 |
st.markdown("---")
|
| 891 |
st.markdown("### π Quick Load")
|
| 892 |
|
| 893 |
-
# Preset dataset buttons
|
| 894 |
col1, col2 = st.columns(2)
|
| 895 |
with col1:
|
| 896 |
if st.button("π 2024 Data", type="primary", key="load_2024"):
|
|
@@ -939,11 +907,9 @@ def main():
|
|
| 939 |
except Exception as e:
|
| 940 |
st.error(f"β Error loading {year} data: {str(e)}")
|
| 941 |
finally:
|
| 942 |
-
# Clear the session state to avoid reloading
|
| 943 |
del st.session_state.load_preset
|
| 944 |
|
| 945 |
if df is not None and stats is not None:
|
| 946 |
-
# Material Overview
|
| 947 |
st.markdown('<div class="section-header">π Material Overview</div>', unsafe_allow_html=True)
|
| 948 |
materials = [k for k in stats.keys() if k != '_total_']
|
| 949 |
|
|
@@ -958,7 +924,6 @@ def main():
|
|
| 958 |
)
|
| 959 |
st.caption(f"Daily avg: {info['daily_avg']:,.0f} kg")
|
| 960 |
|
| 961 |
-
# Handle case where there are fewer than 3 materials or show total in 4th column
|
| 962 |
if len(materials) >= 3:
|
| 963 |
total_info = stats['_total_']
|
| 964 |
with cols[3]:
|
|
@@ -969,7 +934,6 @@ def main():
|
|
| 969 |
)
|
| 970 |
st.caption(f"Daily avg: {total_info['daily_avg']:,.0f} kg")
|
| 971 |
|
| 972 |
-
# Charts Section
|
| 973 |
st.markdown('<div class="section-header">π Production Trends</div>', unsafe_allow_html=True)
|
| 974 |
|
| 975 |
col1, col2 = st.columns([3, 1])
|
|
@@ -983,7 +947,6 @@ def main():
|
|
| 983 |
st.plotly_chart(total_chart, use_container_width=True)
|
| 984 |
st.markdown('</div>', unsafe_allow_html=True)
|
| 985 |
|
| 986 |
-
# Materials Analysis
|
| 987 |
st.markdown('<div class="section-header">π·οΈ Materials Analysis</div>', unsafe_allow_html=True)
|
| 988 |
|
| 989 |
col1, col2 = st.columns([3, 1])
|
|
@@ -1003,7 +966,6 @@ def main():
|
|
| 1003 |
st.plotly_chart(materials_chart, use_container_width=True)
|
| 1004 |
st.markdown('</div>', unsafe_allow_html=True)
|
| 1005 |
|
| 1006 |
-
# Shift Analysis
|
| 1007 |
if 'shift' in df.columns:
|
| 1008 |
st.markdown('<div class="section-header">π Shift Analysis</div>', unsafe_allow_html=True)
|
| 1009 |
|
|
@@ -1013,7 +975,6 @@ def main():
|
|
| 1013 |
st.plotly_chart(shift_chart, use_container_width=True)
|
| 1014 |
st.markdown('</div>', unsafe_allow_html=True)
|
| 1015 |
|
| 1016 |
-
# Quality Check
|
| 1017 |
st.markdown('<div class="section-header">β οΈ Quality Check</div>', unsafe_allow_html=True)
|
| 1018 |
outliers = detect_outliers(df)
|
| 1019 |
|
|
@@ -1032,7 +993,6 @@ def main():
|
|
| 1032 |
|
| 1033 |
add_export_section(df, stats, outliers, model)
|
| 1034 |
|
| 1035 |
-
# AI Assistant
|
| 1036 |
if model:
|
| 1037 |
st.markdown('<div class="section-header">π€ AI Insights</div>', unsafe_allow_html=True)
|
| 1038 |
|
|
@@ -1058,7 +1018,6 @@ def main():
|
|
| 1058 |
st.write(f"**A:** {answer}")
|
| 1059 |
|
| 1060 |
else:
|
| 1061 |
-
# Usage guide when no data is loaded
|
| 1062 |
st.markdown('<div class="section-header">π How to Use This Platform</div>', unsafe_allow_html=True)
|
| 1063 |
|
| 1064 |
col1, col2 = st.columns(2)
|
|
|
|
| 17 |
import os
|
| 18 |
import requests
|
| 19 |
|
|
|
|
| 20 |
DESIGN_SYSTEM = {
|
| 21 |
'colors': {
|
| 22 |
'primary': '#1E40AF',
|
|
|
|
| 35 |
}
|
| 36 |
}
|
| 37 |
|
|
|
|
| 38 |
st.set_page_config(
|
| 39 |
page_title="Production Monitor | Nilsen Service & Consulting",
|
| 40 |
page_icon="π",
|
|
|
|
| 42 |
initial_sidebar_state="expanded"
|
| 43 |
)
|
| 44 |
|
|
|
|
| 45 |
def load_css():
|
| 46 |
st.markdown(f"""
|
| 47 |
<style>
|
|
|
|
| 134 |
|
| 135 |
@st.cache_data
|
| 136 |
def load_preset_data(year):
|
|
|
|
|
|
|
| 137 |
urls = {
|
| 138 |
"2024": "https://huggingface.co/spaces/entropy25/production-data-analysis/resolve/main/2024.csv",
|
| 139 |
"2025": "https://huggingface.co/spaces/entropy25/production-data-analysis/resolve/main/2025.csv"
|
|
|
|
| 155 |
return generate_sample_data(year)
|
| 156 |
|
| 157 |
def generate_sample_data(year):
|
|
|
|
| 158 |
np.random.seed(42 if year == "2024" else 84)
|
| 159 |
|
| 160 |
start_date = f"01/01/{year}"
|
|
|
|
| 352 |
return outliers
|
| 353 |
|
| 354 |
def generate_ai_summary(model, df, stats, outliers):
|
|
|
|
| 355 |
if not model:
|
| 356 |
return "AI analysis unavailable - API key not configured"
|
| 357 |
|
| 358 |
try:
|
|
|
|
| 359 |
materials = [k for k in stats.keys() if k != '_total_']
|
| 360 |
|
|
|
|
| 361 |
context_parts = [
|
| 362 |
"# Production Data Analysis Context",
|
| 363 |
f"## Overview",
|
|
|
|
| 373 |
info = stats[material]
|
| 374 |
context_parts.append(f"- {material.title()}: {info['total']:,.0f} kg ({info['percentage']:.1f}%), avg {info['daily_avg']:,.0f} kg/day")
|
| 375 |
|
|
|
|
| 376 |
daily_data = df.groupby('date')['weight_kg'].sum()
|
| 377 |
trend_direction = "increasing" if daily_data.iloc[-1] > daily_data.iloc[0] else "decreasing"
|
| 378 |
volatility = daily_data.std() / daily_data.mean() * 100
|
|
|
|
| 386 |
f"- Lowest production: {daily_data.min():,.0f} kg"
|
| 387 |
])
|
| 388 |
|
|
|
|
| 389 |
total_outliers = sum(info['count'] for info in outliers.values())
|
| 390 |
context_parts.extend([
|
| 391 |
"",
|
|
|
|
| 394 |
f"- Materials with quality issues: {sum(1 for info in outliers.values() if info['count'] > 0)}"
|
| 395 |
])
|
| 396 |
|
|
|
|
| 397 |
if 'shift' in df.columns:
|
| 398 |
shift_stats = df.groupby('shift')['weight_kg'].sum()
|
| 399 |
context_parts.extend([
|
|
|
|
| 405 |
|
| 406 |
context_text = "\n".join(context_parts)
|
| 407 |
|
|
|
|
| 408 |
prompt = f"""
|
| 409 |
{context_text}
|
| 410 |
|
|
|
|
| 436 |
return f"AI analysis error: {str(e)}"
|
| 437 |
|
| 438 |
def query_ai(model, stats, question, df=None):
|
|
|
|
| 439 |
if not model:
|
| 440 |
return "AI assistant not available"
|
| 441 |
|
|
|
|
| 467 |
return "Error getting AI response"
|
| 468 |
|
| 469 |
def save_plotly_as_image(fig, filename):
|
|
|
|
| 470 |
try:
|
| 471 |
temp_dir = tempfile.gettempdir()
|
| 472 |
filepath = os.path.join(temp_dir, filename)
|
| 473 |
|
| 474 |
+
theme = get_chart_theme()['layout'].copy()
|
| 475 |
+
|
| 476 |
+
theme.update({
|
| 477 |
+
'font': dict(size=12, family="Arial"),
|
| 478 |
+
'plot_bgcolor': 'white',
|
| 479 |
+
'paper_bgcolor': 'white',
|
| 480 |
+
'margin': dict(t=50, b=40, l=40, r=40)
|
| 481 |
+
})
|
| 482 |
+
|
| 483 |
+
fig.update_layout(**theme)
|
| 484 |
|
|
|
|
| 485 |
try:
|
| 486 |
pio.write_image(fig, filepath, format='png', width=800, height=400, scale=2, engine='kaleido')
|
| 487 |
if os.path.exists(filepath):
|
|
|
|
| 495 |
return None
|
| 496 |
|
| 497 |
def create_pdf_charts(df, stats):
|
|
|
|
| 498 |
charts = {}
|
| 499 |
|
| 500 |
try:
|
|
|
|
| 542 |
return charts
|
| 543 |
|
| 544 |
def create_enhanced_pdf_report(df, stats, outliers, model=None):
|
|
|
|
| 545 |
buffer = io.BytesIO()
|
| 546 |
doc = SimpleDocTemplate(buffer, pagesize=A4, rightMargin=50, leftMargin=50, topMargin=50, bottomMargin=50)
|
| 547 |
|
| 548 |
elements = []
|
| 549 |
styles = getSampleStyleSheet()
|
| 550 |
|
|
|
|
| 551 |
title_style = ParagraphStyle(
|
| 552 |
'CustomTitle',
|
| 553 |
parent=styles['Heading1'],
|
|
|
|
| 574 |
textColor=colors.darkgreen
|
| 575 |
)
|
| 576 |
|
|
|
|
| 577 |
elements.append(Spacer(1, 100))
|
| 578 |
elements.append(Paragraph("Production Monitor Report", title_style))
|
| 579 |
elements.append(Paragraph("Comprehensive Production Analysis with AI Insights", styles['Heading3']))
|
| 580 |
elements.append(Spacer(1, 50))
|
| 581 |
|
|
|
|
| 582 |
report_info = f"""
|
| 583 |
<para alignment="center">
|
| 584 |
<b>Nilsen Service & Consulting AS</b><br/>
|
|
|
|
| 591 |
elements.append(Paragraph(report_info, styles['Normal']))
|
| 592 |
elements.append(PageBreak())
|
| 593 |
|
|
|
|
| 594 |
elements.append(Paragraph("Executive Summary", subtitle_style))
|
| 595 |
|
| 596 |
total_production = stats['_total_']['total']
|
|
|
|
| 613 |
elements.append(Paragraph(exec_summary, styles['Normal']))
|
| 614 |
elements.append(Spacer(1, 20))
|
| 615 |
|
|
|
|
| 616 |
elements.append(Paragraph("Production Summary", styles['Heading3']))
|
| 617 |
|
| 618 |
summary_data = [['Material Type', 'Total (kg)', 'Share (%)', 'Daily Avg (kg)']]
|
|
|
|
| 639 |
elements.append(summary_table)
|
| 640 |
elements.append(PageBreak())
|
| 641 |
|
|
|
|
| 642 |
elements.append(Paragraph("Production Analysis Charts", subtitle_style))
|
| 643 |
|
| 644 |
try:
|
|
|
|
| 648 |
|
| 649 |
charts_added = False
|
| 650 |
|
|
|
|
| 651 |
chart_insights = {
|
| 652 |
'pie': "Material distribution shows production allocation across different materials. Balanced distribution indicates diversified production capabilities.",
|
| 653 |
'trend': "Production trend reveals operational patterns and seasonal variations. Consistent trends suggest stable operational efficiency.",
|
|
|
|
| 667 |
elements.append(Paragraph(chart_title, styles['Heading3']))
|
| 668 |
elements.append(Image(chart_path, width=6*inch, height=3*inch))
|
| 669 |
|
|
|
|
| 670 |
insight_text = f"<i>Analysis: {chart_insights.get(chart_type, 'Chart analysis not available.')}</i>"
|
| 671 |
elements.append(Paragraph(insight_text, ai_style))
|
| 672 |
elements.append(Spacer(1, 20))
|
|
|
|
| 683 |
elements.append(Paragraph(summary_text, styles['Normal']))
|
| 684 |
elements.append(Spacer(1, 20))
|
| 685 |
|
|
|
|
| 686 |
elements.append(PageBreak())
|
| 687 |
elements.append(Paragraph("Quality Control Analysis", subtitle_style))
|
| 688 |
|
|
|
|
| 715 |
|
| 716 |
elements.append(quality_table)
|
| 717 |
|
|
|
|
| 718 |
if model:
|
| 719 |
elements.append(PageBreak())
|
| 720 |
elements.append(Paragraph("AI Intelligent Analysis", subtitle_style))
|
|
|
|
| 724 |
except:
|
| 725 |
ai_analysis = "AI analysis temporarily unavailable."
|
| 726 |
|
|
|
|
| 727 |
ai_paragraphs = ai_analysis.split('\n\n')
|
| 728 |
for paragraph in ai_paragraphs:
|
| 729 |
if paragraph.strip():
|
|
|
|
| 730 |
formatted_text = paragraph.replace('**', '<b>', 1).replace('**', '</b>', 1)
|
| 731 |
+
formatted_text = formatted_text.replace('β’', ' β’')
|
| 732 |
elements.append(Paragraph(formatted_text, styles['Normal']))
|
| 733 |
elements.append(Spacer(1, 8))
|
| 734 |
else:
|
|
|
|
| 736 |
elements.append(Paragraph("AI Analysis", subtitle_style))
|
| 737 |
elements.append(Paragraph("AI analysis unavailable - API key not configured. Please configure Google AI API key to enable intelligent insights.", styles['Normal']))
|
| 738 |
|
|
|
|
| 739 |
elements.append(Spacer(1, 30))
|
| 740 |
footer_text = f"""
|
| 741 |
<para alignment="center">
|
|
|
|
| 751 |
return buffer
|
| 752 |
|
| 753 |
def create_csv_export(df, stats):
|
|
|
|
| 754 |
summary_df = pd.DataFrame([
|
| 755 |
{
|
| 756 |
'Material': material.replace('_', ' ').title(),
|
|
|
|
| 765 |
|
| 766 |
return summary_df
|
| 767 |
|
|
|
|
| 768 |
def add_export_section(df, stats, outliers, model):
|
| 769 |
st.markdown('<div class="section-header">π Export Reports</div>', unsafe_allow_html=True)
|
| 770 |
|
|
|
|
| 833 |
st.session_state.pdf_buffer = None
|
| 834 |
st.session_state.csv_data = None
|
| 835 |
st.rerun()
|
| 836 |
+
|
| 837 |
def main():
|
| 838 |
load_css()
|
| 839 |
|
|
|
|
| 840 |
st.markdown("""
|
| 841 |
<div class="main-header">
|
| 842 |
<div class="main-title">π Production Monitor</div>
|
|
|
|
| 851 |
if 'current_stats' not in st.session_state:
|
| 852 |
st.session_state.current_stats = None
|
| 853 |
|
|
|
|
| 854 |
with st.sidebar:
|
| 855 |
st.markdown("### π Data Source")
|
| 856 |
|
|
|
|
| 857 |
uploaded_file = st.file_uploader("Upload Production Data", type=['csv'])
|
| 858 |
|
| 859 |
st.markdown("---")
|
| 860 |
st.markdown("### π Quick Load")
|
| 861 |
|
|
|
|
| 862 |
col1, col2 = st.columns(2)
|
| 863 |
with col1:
|
| 864 |
if st.button("π 2024 Data", type="primary", key="load_2024"):
|
|
|
|
| 907 |
except Exception as e:
|
| 908 |
st.error(f"β Error loading {year} data: {str(e)}")
|
| 909 |
finally:
|
|
|
|
| 910 |
del st.session_state.load_preset
|
| 911 |
|
| 912 |
if df is not None and stats is not None:
|
|
|
|
| 913 |
st.markdown('<div class="section-header">π Material Overview</div>', unsafe_allow_html=True)
|
| 914 |
materials = [k for k in stats.keys() if k != '_total_']
|
| 915 |
|
|
|
|
| 924 |
)
|
| 925 |
st.caption(f"Daily avg: {info['daily_avg']:,.0f} kg")
|
| 926 |
|
|
|
|
| 927 |
if len(materials) >= 3:
|
| 928 |
total_info = stats['_total_']
|
| 929 |
with cols[3]:
|
|
|
|
| 934 |
)
|
| 935 |
st.caption(f"Daily avg: {total_info['daily_avg']:,.0f} kg")
|
| 936 |
|
|
|
|
| 937 |
st.markdown('<div class="section-header">π Production Trends</div>', unsafe_allow_html=True)
|
| 938 |
|
| 939 |
col1, col2 = st.columns([3, 1])
|
|
|
|
| 947 |
st.plotly_chart(total_chart, use_container_width=True)
|
| 948 |
st.markdown('</div>', unsafe_allow_html=True)
|
| 949 |
|
|
|
|
| 950 |
st.markdown('<div class="section-header">π·οΈ Materials Analysis</div>', unsafe_allow_html=True)
|
| 951 |
|
| 952 |
col1, col2 = st.columns([3, 1])
|
|
|
|
| 966 |
st.plotly_chart(materials_chart, use_container_width=True)
|
| 967 |
st.markdown('</div>', unsafe_allow_html=True)
|
| 968 |
|
|
|
|
| 969 |
if 'shift' in df.columns:
|
| 970 |
st.markdown('<div class="section-header">π Shift Analysis</div>', unsafe_allow_html=True)
|
| 971 |
|
|
|
|
| 975 |
st.plotly_chart(shift_chart, use_container_width=True)
|
| 976 |
st.markdown('</div>', unsafe_allow_html=True)
|
| 977 |
|
|
|
|
| 978 |
st.markdown('<div class="section-header">β οΈ Quality Check</div>', unsafe_allow_html=True)
|
| 979 |
outliers = detect_outliers(df)
|
| 980 |
|
|
|
|
| 993 |
|
| 994 |
add_export_section(df, stats, outliers, model)
|
| 995 |
|
|
|
|
| 996 |
if model:
|
| 997 |
st.markdown('<div class="section-header">π€ AI Insights</div>', unsafe_allow_html=True)
|
| 998 |
|
|
|
|
| 1018 |
st.write(f"**A:** {answer}")
|
| 1019 |
|
| 1020 |
else:
|
|
|
|
| 1021 |
st.markdown('<div class="section-header">π How to Use This Platform</div>', unsafe_allow_html=True)
|
| 1022 |
|
| 1023 |
col1, col2 = st.columns(2)
|