Spaces:
Sleeping
Sleeping
Commit ·
39aec55
1
Parent(s): 9bdbae8
Update PDF utils and translations
Browse files- utils/pdf_utils.py +92 -93
- utils/translations.py +0 -114
utils/pdf_utils.py
CHANGED
|
@@ -278,7 +278,7 @@ class PDFReportGenerator:
|
|
| 278 |
story.extend(self._create_results_header_section(analysis_data, metadata))
|
| 279 |
except Exception as e:
|
| 280 |
logger.error(f"Error creating results header: {str(e)}")
|
| 281 |
-
story.append(Paragraph(
|
| 282 |
|
| 283 |
try:
|
| 284 |
# 2. Executive Summary (if enabled) - COPY EXACTLY FROM RESULTS PAGE
|
|
@@ -286,8 +286,8 @@ class PDFReportGenerator:
|
|
| 286 |
story.extend(self._create_enhanced_executive_summary(analysis_data))
|
| 287 |
except Exception as e:
|
| 288 |
logger.error(f"Error creating executive summary: {str(e)}")
|
| 289 |
-
story.append(Paragraph(
|
| 290 |
-
story.append(Paragraph(
|
| 291 |
|
| 292 |
|
| 293 |
try:
|
|
@@ -580,7 +580,7 @@ class PDFReportGenerator:
|
|
| 580 |
story = []
|
| 581 |
|
| 582 |
# Executive Summary header
|
| 583 |
-
story.append(Paragraph(
|
| 584 |
story.append(Spacer(1, 12))
|
| 585 |
|
| 586 |
# Handle data structure - analysis_data might be the analysis_results content directly
|
|
@@ -609,8 +609,7 @@ class PDFReportGenerator:
|
|
| 609 |
return story
|
| 610 |
|
| 611 |
# Fallback if generation fails
|
| 612 |
-
|
| 613 |
-
story.append(Paragraph(fallback_text, self.styles['CustomBody']))
|
| 614 |
story.append(Spacer(1, 12))
|
| 615 |
return story
|
| 616 |
|
|
@@ -1383,7 +1382,7 @@ class PDFReportGenerator:
|
|
| 1383 |
|
| 1384 |
def _create_step1_pdf_content(self, story, analysis_data, main_analysis_results=None):
|
| 1385 |
"""Create Step 1 PDF content matching results page format"""
|
| 1386 |
-
story.append(Paragraph(
|
| 1387 |
story.append(Spacer(1, 8))
|
| 1388 |
|
| 1389 |
# Debug: Log what data is available
|
|
@@ -1402,7 +1401,7 @@ class PDFReportGenerator:
|
|
| 1402 |
|
| 1403 |
# Summary section
|
| 1404 |
if 'summary' in analysis_data and analysis_data['summary']:
|
| 1405 |
-
story.append(Paragraph(
|
| 1406 |
summary_text = analysis_data['summary']
|
| 1407 |
if isinstance(summary_text, str) and summary_text.strip():
|
| 1408 |
story.append(Paragraph(self._sanitize_text_persona(summary_text.strip()), self.styles['CustomBody']))
|
|
@@ -1410,7 +1409,7 @@ class PDFReportGenerator:
|
|
| 1410 |
|
| 1411 |
# Detailed Analysis section
|
| 1412 |
if 'detailed_analysis' in analysis_data and analysis_data['detailed_analysis']:
|
| 1413 |
-
story.append(Paragraph(
|
| 1414 |
detailed_text = analysis_data['detailed_analysis']
|
| 1415 |
|
| 1416 |
if isinstance(detailed_text, dict):
|
|
@@ -1432,7 +1431,7 @@ class PDFReportGenerator:
|
|
| 1432 |
story.append(Spacer(1, 8))
|
| 1433 |
|
| 1434 |
# Data Tables section
|
| 1435 |
-
story.append(Paragraph(
|
| 1436 |
story.append(Spacer(1, 6))
|
| 1437 |
|
| 1438 |
# Your Soil and Leaf Test Results table
|
|
@@ -1521,7 +1520,7 @@ class PDFReportGenerator:
|
|
| 1521 |
|
| 1522 |
# Summary section
|
| 1523 |
if 'summary' in analysis_data and analysis_data['summary']:
|
| 1524 |
-
story.append(Paragraph(
|
| 1525 |
summary_text = analysis_data['summary']
|
| 1526 |
if isinstance(summary_text, str) and summary_text.strip():
|
| 1527 |
story.append(Paragraph(self._sanitize_text_persona(summary_text.strip()), self.styles['CustomBody']))
|
|
@@ -1529,7 +1528,7 @@ class PDFReportGenerator:
|
|
| 1529 |
|
| 1530 |
# Detailed Analysis section
|
| 1531 |
if 'detailed_analysis' in analysis_data and analysis_data['detailed_analysis']:
|
| 1532 |
-
story.append(Paragraph(
|
| 1533 |
detailed_text = analysis_data['detailed_analysis']
|
| 1534 |
|
| 1535 |
if isinstance(detailed_text, dict):
|
|
@@ -1552,7 +1551,7 @@ class PDFReportGenerator:
|
|
| 1552 |
|
| 1553 |
# Tables section (consistent with Step 2)
|
| 1554 |
if 'tables' in analysis_data and analysis_data['tables']:
|
| 1555 |
-
story.append(Paragraph(
|
| 1556 |
tables = analysis_data['tables']
|
| 1557 |
if isinstance(tables, list):
|
| 1558 |
for table in tables:
|
|
@@ -1589,7 +1588,7 @@ class PDFReportGenerator:
|
|
| 1589 |
"""Create standard step PDF content for steps 2, 4, 5, 6"""
|
| 1590 |
# Summary section
|
| 1591 |
if 'summary' in analysis_data and analysis_data['summary']:
|
| 1592 |
-
story.append(Paragraph(
|
| 1593 |
summary_text = analysis_data['summary']
|
| 1594 |
if isinstance(summary_text, str) and summary_text.strip():
|
| 1595 |
# Apply comprehensive cleaning (same as analysis engine)
|
|
@@ -1601,7 +1600,7 @@ class PDFReportGenerator:
|
|
| 1601 |
|
| 1602 |
# Detailed Analysis section
|
| 1603 |
if 'detailed_analysis' in analysis_data and analysis_data['detailed_analysis']:
|
| 1604 |
-
story.append(Paragraph(
|
| 1605 |
detailed_text = analysis_data['detailed_analysis']
|
| 1606 |
|
| 1607 |
if isinstance(detailed_text, dict):
|
|
@@ -1624,7 +1623,7 @@ class PDFReportGenerator:
|
|
| 1624 |
|
| 1625 |
# Tables section
|
| 1626 |
if 'tables' in analysis_data and analysis_data['tables']:
|
| 1627 |
-
story.append(Paragraph(
|
| 1628 |
tables = analysis_data['tables']
|
| 1629 |
if isinstance(tables, list):
|
| 1630 |
for table in tables:
|
|
@@ -3741,12 +3740,12 @@ class PDFReportGenerator:
|
|
| 3741 |
# If still no steps, create a comprehensive fallback message
|
| 3742 |
if not step_results:
|
| 3743 |
logger.warning("🔍 DEBUG - No step data found anywhere, creating comprehensive fallback content")
|
| 3744 |
-
story.append(Paragraph(
|
| 3745 |
-
story.append(Paragraph(
|
| 3746 |
|
| 3747 |
# Add key findings if available
|
| 3748 |
if 'key_findings' in analysis_results:
|
| 3749 |
-
story.append(Paragraph(
|
| 3750 |
key_findings = analysis_results['key_findings']
|
| 3751 |
normalized_kf = []
|
| 3752 |
|
|
@@ -3776,13 +3775,13 @@ class PDFReportGenerator:
|
|
| 3776 |
|
| 3777 |
# Add summary if available
|
| 3778 |
if 'summary' in analysis_results:
|
| 3779 |
-
story.append(Paragraph(
|
| 3780 |
story.append(Paragraph(str(analysis_results['summary']), self.styles['CustomBody']))
|
| 3781 |
story.append(Spacer(1, 8))
|
| 3782 |
|
| 3783 |
# Add detailed analysis if available
|
| 3784 |
if 'detailed_analysis' in analysis_results:
|
| 3785 |
-
story.append(Paragraph(
|
| 3786 |
story.append(Paragraph(str(analysis_results['detailed_analysis']), self.styles['CustomBody']))
|
| 3787 |
story.append(Spacer(1, 8))
|
| 3788 |
|
|
@@ -3844,7 +3843,7 @@ class PDFReportGenerator:
|
|
| 3844 |
|
| 3845 |
# Statistical Analysis (from enhanced LLM output)
|
| 3846 |
if 'statistical_analysis' in step and step['statistical_analysis']:
|
| 3847 |
-
story.append(Paragraph(
|
| 3848 |
if isinstance(step['statistical_analysis'], dict):
|
| 3849 |
for key, value in step['statistical_analysis'].items():
|
| 3850 |
story.append(Paragraph(f"<b>{key.replace('_', ' ').title()}:</b> {value}", self.styles['CustomBody']))
|
|
@@ -3854,7 +3853,7 @@ class PDFReportGenerator:
|
|
| 3854 |
|
| 3855 |
# Issues Identified (crucial for farmers)
|
| 3856 |
if 'issues_identified' in step and step['issues_identified']:
|
| 3857 |
-
story.append(Paragraph(
|
| 3858 |
for i, issue in enumerate(step['issues_identified'], 1):
|
| 3859 |
issue_text = f"<b>{i}.</b> {issue}"
|
| 3860 |
story.append(Paragraph(issue_text, self.styles['CustomBody']))
|
|
@@ -3862,7 +3861,7 @@ class PDFReportGenerator:
|
|
| 3862 |
|
| 3863 |
# Key Findings (from enhanced LLM output)
|
| 3864 |
if 'key_findings' in step and step['key_findings']:
|
| 3865 |
-
story.append(Paragraph(
|
| 3866 |
key_findings = step['key_findings']
|
| 3867 |
normalized_kf = []
|
| 3868 |
|
|
@@ -3895,7 +3894,7 @@ class PDFReportGenerator:
|
|
| 3895 |
|
| 3896 |
# Legacy recommendations (for backward compatibility)
|
| 3897 |
if 'recommendations' in step and step['recommendations']:
|
| 3898 |
-
story.append(Paragraph(
|
| 3899 |
for i, rec in enumerate(step['recommendations'], 1):
|
| 3900 |
rec_text = f"<b>{i}.</b> {rec}"
|
| 3901 |
story.append(Paragraph(rec_text, self.styles['CustomBody']))
|
|
@@ -3912,7 +3911,7 @@ class PDFReportGenerator:
|
|
| 3912 |
# Explicitly list specific recommendations if provided
|
| 3913 |
specific_recs = step.get('specific_recommendations', [])
|
| 3914 |
if isinstance(specific_recs, list) and specific_recs:
|
| 3915 |
-
story.append(Paragraph(
|
| 3916 |
for i, rec in enumerate(specific_recs, 1):
|
| 3917 |
story.append(Paragraph(f"{i}. {rec}", self.styles['CustomBody']))
|
| 3918 |
story.append(Spacer(1, 8))
|
|
@@ -3948,7 +3947,7 @@ class PDFReportGenerator:
|
|
| 3948 |
|
| 3949 |
if yield_chart is not None:
|
| 3950 |
logger.info("🔍 DEBUG Step 6 - Adding chart to story")
|
| 3951 |
-
story.append(Paragraph(
|
| 3952 |
story.append(Spacer(1, 8))
|
| 3953 |
story.append(yield_chart)
|
| 3954 |
story.append(Spacer(1, 12))
|
|
@@ -3956,17 +3955,17 @@ class PDFReportGenerator:
|
|
| 3956 |
else:
|
| 3957 |
logger.warning("❌ Step 6: Yield forecast chart is None")
|
| 3958 |
logger.info("🔍 DEBUG Step 6 - Chart is None, adding failure message")
|
| 3959 |
-
story.append(Paragraph(
|
| 3960 |
story.append(Spacer(1, 8))
|
| 3961 |
-
story.append(Paragraph(
|
| 3962 |
|
| 3963 |
except Exception as e:
|
| 3964 |
logger.error(f"❌ Step 6: Error adding yield forecast chart: {str(e)}")
|
| 3965 |
import traceback
|
| 3966 |
logger.error(f"Step 6 Full traceback: {traceback.format_exc()}")
|
| 3967 |
-
story.append(Paragraph(
|
| 3968 |
story.append(Spacer(1, 8))
|
| 3969 |
-
story.append(Paragraph(
|
| 3970 |
|
| 3971 |
# Visualizations and Charts - ONLY Step 1 bar graphs; remove charts for Steps 2-6
|
| 3972 |
try:
|
|
@@ -6748,7 +6747,7 @@ class PDFReportGenerator:
|
|
| 6748 |
return story
|
| 6749 |
|
| 6750 |
# Economic Impact Forecast header
|
| 6751 |
-
story.append(Paragraph(
|
| 6752 |
story.append(Spacer(1, 12))
|
| 6753 |
|
| 6754 |
# Find economic forecast data from multiple possible locations
|
|
@@ -6802,24 +6801,24 @@ class PDFReportGenerator:
|
|
| 6802 |
|
| 6803 |
# Display basic information
|
| 6804 |
if current_yield > 0:
|
| 6805 |
-
story.append(Paragraph(f"<b>
|
| 6806 |
else:
|
| 6807 |
-
story.append(Paragraph(f"<b>
|
| 6808 |
|
| 6809 |
if land_size > 0:
|
| 6810 |
-
story.append(Paragraph(f"<b>
|
| 6811 |
|
| 6812 |
# Add palm density information if available
|
| 6813 |
palm_density = econ.get('palm_density_per_hectare', 0)
|
| 6814 |
total_palms = econ.get('total_palms', 0)
|
| 6815 |
if palm_density > 0:
|
| 6816 |
-
story.append(Paragraph(f"<b>
|
| 6817 |
if total_palms > 0:
|
| 6818 |
-
story.append(Paragraph(f"<b>
|
| 6819 |
|
| 6820 |
# Use FFB price range for consistency
|
| 6821 |
ffb_price_range = econ.get('oil_palm_price_range_rm_per_tonne', 'RM 650-750')
|
| 6822 |
-
story.append(Paragraph(f"<b>
|
| 6823 |
story.append(Spacer(1, 12))
|
| 6824 |
|
| 6825 |
# Remove Economic Forecast Assumptions section as requested
|
|
@@ -6832,17 +6831,17 @@ class PDFReportGenerator:
|
|
| 6832 |
# Fallback to Year-1 only display if no scenario data available
|
| 6833 |
year1 = econ.get('year_1', {}) if isinstance(econ, dict) else {}
|
| 6834 |
if year1:
|
| 6835 |
-
story.append(Paragraph(
|
| 6836 |
story.append(Spacer(1, 6))
|
| 6837 |
# Build a simple key/value table from known fields, falling back gracefully
|
| 6838 |
keys = [
|
| 6839 |
-
('new_yield_tpha',
|
| 6840 |
-
('additional_yield_tpha',
|
| 6841 |
-
('additional_revenue_rm',
|
| 6842 |
-
('cost_per_hectare_rm',
|
| 6843 |
# Prefer range if available; fall back to roi_percentage with cap note
|
| 6844 |
-
('roi_percentage_range',
|
| 6845 |
-
('payback_months',
|
| 6846 |
]
|
| 6847 |
rows = []
|
| 6848 |
for k, label in keys:
|
|
@@ -6852,12 +6851,12 @@ class PDFReportGenerator:
|
|
| 6852 |
if k == 'roi_percentage_range' and isinstance(v, str):
|
| 6853 |
display_value = v
|
| 6854 |
elif 'roi_percentage' in k and isinstance(v, (int, float)):
|
| 6855 |
-
display_value = f"{60}% (
|
| 6856 |
else:
|
| 6857 |
display_value = str(v)
|
| 6858 |
rows.append([label, display_value])
|
| 6859 |
if rows:
|
| 6860 |
-
table = self._create_table_with_proper_layout([[
|
| 6861 |
if table:
|
| 6862 |
story.append(table)
|
| 6863 |
story.append(Spacer(1, 12))
|
|
@@ -6868,24 +6867,24 @@ class PDFReportGenerator:
|
|
| 6868 |
story.append(Paragraph("<i>Note: RM values are based on current market rates and typical plantation economics.</i>", self.styles['CustomBody']))
|
| 6869 |
else:
|
| 6870 |
# Create a basic economic forecast when data is not available
|
| 6871 |
-
story.append(Paragraph(
|
| 6872 |
story.append(Spacer(1, 8))
|
| 6873 |
|
| 6874 |
# Basic economic information
|
| 6875 |
-
story.append(Paragraph(
|
| 6876 |
-
story.append(Paragraph(
|
| 6877 |
-
story.append(Paragraph(
|
| 6878 |
story.append(Spacer(1, 12))
|
| 6879 |
|
| 6880 |
# Basic cost-benefit table
|
| 6881 |
-
story.append(Paragraph(
|
| 6882 |
story.append(Spacer(1, 8))
|
| 6883 |
|
| 6884 |
table_data = [
|
| 6885 |
-
[
|
| 6886 |
-
[
|
| 6887 |
-
[
|
| 6888 |
-
[
|
| 6889 |
]
|
| 6890 |
|
| 6891 |
col_widths = [
|
|
@@ -6911,7 +6910,7 @@ class PDFReportGenerator:
|
|
| 6911 |
story = []
|
| 6912 |
|
| 6913 |
# 5-Year Yield Forecast header
|
| 6914 |
-
story.append(Paragraph(
|
| 6915 |
story.append(Spacer(1, 12))
|
| 6916 |
|
| 6917 |
# Find yield forecast data from multiple possible locations
|
|
@@ -7124,7 +7123,7 @@ class PDFReportGenerator:
|
|
| 7124 |
story = []
|
| 7125 |
|
| 7126 |
# Conclusion header
|
| 7127 |
-
story.append(Paragraph(
|
| 7128 |
story.append(Spacer(1, 12))
|
| 7129 |
|
| 7130 |
# Extract key data for personalized conclusion
|
|
@@ -7136,42 +7135,42 @@ class PDFReportGenerator:
|
|
| 7136 |
conclusion_parts = []
|
| 7137 |
|
| 7138 |
# Analysis overview
|
| 7139 |
-
conclusion_parts.append(
|
| 7140 |
-
<b>
|
| 7141 |
-
|
| 7142 |
""")
|
| 7143 |
|
| 7144 |
# Key findings summary
|
| 7145 |
if step_analysis:
|
| 7146 |
-
conclusion_parts.append(
|
| 7147 |
-
<b>
|
| 7148 |
-
|
| 7149 |
""")
|
| 7150 |
|
| 7151 |
# Economic impact
|
| 7152 |
if economic_forecast:
|
| 7153 |
-
conclusion_parts.append(
|
| 7154 |
-
<b>
|
| 7155 |
-
|
| 7156 |
""")
|
| 7157 |
|
| 7158 |
# Yield projections
|
| 7159 |
if yield_forecast:
|
| 7160 |
-
conclusion_parts.append(
|
| 7161 |
-
<b>
|
| 7162 |
-
|
| 7163 |
""")
|
| 7164 |
|
| 7165 |
# Implementation recommendations
|
| 7166 |
-
conclusion_parts.append(
|
| 7167 |
-
<b>
|
| 7168 |
-
|
| 7169 |
""")
|
| 7170 |
|
| 7171 |
# Long-term outlook
|
| 7172 |
-
conclusion_parts.append(
|
| 7173 |
-
<b>
|
| 7174 |
-
|
| 7175 |
""")
|
| 7176 |
|
| 7177 |
# Combine all conclusion parts
|
|
@@ -7181,9 +7180,9 @@ class PDFReportGenerator:
|
|
| 7181 |
story.append(Spacer(1, 20))
|
| 7182 |
|
| 7183 |
# Add final summary paragraph
|
| 7184 |
-
final_summary =
|
| 7185 |
-
<b>
|
| 7186 |
-
|
| 7187 |
"""
|
| 7188 |
|
| 7189 |
story.append(Paragraph(final_summary, self.styles['CustomBody']))
|
|
@@ -7196,7 +7195,7 @@ class PDFReportGenerator:
|
|
| 7196 |
story = []
|
| 7197 |
|
| 7198 |
# Results header
|
| 7199 |
-
story.append(Paragraph(
|
| 7200 |
story.append(Spacer(1, 12))
|
| 7201 |
|
| 7202 |
# Create simplified metadata table without debug information
|
|
@@ -7209,12 +7208,12 @@ class PDFReportGenerator:
|
|
| 7209 |
formatted_time = timestamp.strftime("%Y-%m-%d")
|
| 7210 |
else:
|
| 7211 |
formatted_time = str(timestamp)[:10] # Just the date part
|
| 7212 |
-
metadata_data.append([
|
| 7213 |
|
| 7214 |
# Report Types only
|
| 7215 |
report_types = analysis_data.get('report_types', ['soil', 'leaf'])
|
| 7216 |
if report_types:
|
| 7217 |
-
metadata_data.append([
|
| 7218 |
|
| 7219 |
if metadata_data:
|
| 7220 |
metadata_table = self._create_table_with_proper_layout(metadata_data)
|
|
@@ -7238,7 +7237,7 @@ class PDFReportGenerator:
|
|
| 7238 |
story = []
|
| 7239 |
|
| 7240 |
# Raw Data header
|
| 7241 |
-
story.append(Paragraph(
|
| 7242 |
story.append(Spacer(1, 12))
|
| 7243 |
|
| 7244 |
# Get raw data from analysis
|
|
@@ -7248,11 +7247,11 @@ class PDFReportGenerator:
|
|
| 7248 |
|
| 7249 |
# Soil parameters table
|
| 7250 |
if soil_params:
|
| 7251 |
-
story.append(Paragraph(
|
| 7252 |
story.append(Spacer(1, 8))
|
| 7253 |
|
| 7254 |
# Create soil parameters table
|
| 7255 |
-
soil_data = [[
|
| 7256 |
for param, data in soil_params.items():
|
| 7257 |
if isinstance(data, dict) and 'average' in data:
|
| 7258 |
unit = data.get('unit', '')
|
|
@@ -7281,11 +7280,11 @@ class PDFReportGenerator:
|
|
| 7281 |
|
| 7282 |
# Leaf parameters table
|
| 7283 |
if leaf_params:
|
| 7284 |
-
story.append(Paragraph(
|
| 7285 |
story.append(Spacer(1, 8))
|
| 7286 |
|
| 7287 |
# Create leaf parameters table
|
| 7288 |
-
leaf_data = [[
|
| 7289 |
for param, data in leaf_params.items():
|
| 7290 |
if isinstance(data, dict) and 'average' in data:
|
| 7291 |
unit = data.get('unit', '')
|
|
@@ -7314,7 +7313,7 @@ class PDFReportGenerator:
|
|
| 7314 |
story.append(Spacer(1, 12))
|
| 7315 |
|
| 7316 |
if not soil_params and not leaf_params:
|
| 7317 |
-
story.append(Paragraph(
|
| 7318 |
|
| 7319 |
story.append(Spacer(1, 20))
|
| 7320 |
return story
|
|
@@ -7324,7 +7323,7 @@ class PDFReportGenerator:
|
|
| 7324 |
story = []
|
| 7325 |
|
| 7326 |
# References header
|
| 7327 |
-
story.append(Paragraph(
|
| 7328 |
story.append(Spacer(1, 12))
|
| 7329 |
|
| 7330 |
# Get references from analysis data
|
|
@@ -7334,12 +7333,12 @@ class PDFReportGenerator:
|
|
| 7334 |
total_refs = len(all_references.get('database_references', []))
|
| 7335 |
|
| 7336 |
if total_refs > 0:
|
| 7337 |
-
story.append(Paragraph(f"<b>
|
| 7338 |
story.append(Spacer(1, 12))
|
| 7339 |
|
| 7340 |
# Database references only
|
| 7341 |
if all_references['database_references']:
|
| 7342 |
-
story.append(Paragraph(
|
| 7343 |
story.append(Spacer(1, 8))
|
| 7344 |
|
| 7345 |
for i, ref in enumerate(all_references['database_references'], 1):
|
|
@@ -9514,7 +9513,7 @@ class PDFReportGenerator:
|
|
| 9514 |
if 'tables' in data and data['tables']:
|
| 9515 |
tables = data['tables']
|
| 9516 |
if isinstance(tables, list):
|
| 9517 |
-
story.append(Paragraph(
|
| 9518 |
story.append(Spacer(1, 8))
|
| 9519 |
for i, table_data in enumerate(tables, 1):
|
| 9520 |
if not isinstance(table_data, dict):
|
|
@@ -9731,4 +9730,4 @@ def generate_pdf_report(analysis_data: Dict[str, Any], metadata: Dict[str, Any],
|
|
| 9731 |
if para_text:
|
| 9732 |
elements.append(Paragraph(self._sanitize_text_persona(para_text), self.styles['CustomBody']))
|
| 9733 |
|
| 9734 |
-
return elements
|
|
|
|
| 278 |
story.extend(self._create_results_header_section(analysis_data, metadata))
|
| 279 |
except Exception as e:
|
| 280 |
logger.error(f"Error creating results header: {str(e)}")
|
| 281 |
+
story.append(Paragraph("Analysis Results", self.styles['Heading1']))
|
| 282 |
|
| 283 |
try:
|
| 284 |
# 2. Executive Summary (if enabled) - COPY EXACTLY FROM RESULTS PAGE
|
|
|
|
| 286 |
story.extend(self._create_enhanced_executive_summary(analysis_data))
|
| 287 |
except Exception as e:
|
| 288 |
logger.error(f"Error creating executive summary: {str(e)}")
|
| 289 |
+
story.append(Paragraph("Executive Summary", self.styles['Heading2']))
|
| 290 |
+
story.append(Paragraph("Summary could not be generated due to technical issues.", self.styles['Normal']))
|
| 291 |
|
| 292 |
|
| 293 |
try:
|
|
|
|
| 580 |
story = []
|
| 581 |
|
| 582 |
# Executive Summary header
|
| 583 |
+
story.append(Paragraph("Executive Summary", self.styles['Heading1']))
|
| 584 |
story.append(Spacer(1, 12))
|
| 585 |
|
| 586 |
# Handle data structure - analysis_data might be the analysis_results content directly
|
|
|
|
| 609 |
return story
|
| 610 |
|
| 611 |
# Fallback if generation fails
|
| 612 |
+
story.append(Paragraph("Executive summary could not be generated from the analysis data.", self.styles['CustomBody']))
|
|
|
|
| 613 |
story.append(Spacer(1, 12))
|
| 614 |
return story
|
| 615 |
|
|
|
|
| 1382 |
|
| 1383 |
def _create_step1_pdf_content(self, story, analysis_data, main_analysis_results=None):
|
| 1384 |
"""Create Step 1 PDF content matching results page format"""
|
| 1385 |
+
story.append(Paragraph("📊 Data Analysis Results", self.styles['Heading2']))
|
| 1386 |
story.append(Spacer(1, 8))
|
| 1387 |
|
| 1388 |
# Debug: Log what data is available
|
|
|
|
| 1401 |
|
| 1402 |
# Summary section
|
| 1403 |
if 'summary' in analysis_data and analysis_data['summary']:
|
| 1404 |
+
story.append(Paragraph("📋 Summary", self.styles['Heading3']))
|
| 1405 |
summary_text = analysis_data['summary']
|
| 1406 |
if isinstance(summary_text, str) and summary_text.strip():
|
| 1407 |
story.append(Paragraph(self._sanitize_text_persona(summary_text.strip()), self.styles['CustomBody']))
|
|
|
|
| 1409 |
|
| 1410 |
# Detailed Analysis section
|
| 1411 |
if 'detailed_analysis' in analysis_data and analysis_data['detailed_analysis']:
|
| 1412 |
+
story.append(Paragraph("📋 Detailed Analysis", self.styles['Heading3']))
|
| 1413 |
detailed_text = analysis_data['detailed_analysis']
|
| 1414 |
|
| 1415 |
if isinstance(detailed_text, dict):
|
|
|
|
| 1431 |
story.append(Spacer(1, 8))
|
| 1432 |
|
| 1433 |
# Data Tables section
|
| 1434 |
+
story.append(Paragraph("📊 Data Tables", self.styles['Heading3']))
|
| 1435 |
story.append(Spacer(1, 6))
|
| 1436 |
|
| 1437 |
# Your Soil and Leaf Test Results table
|
|
|
|
| 1520 |
|
| 1521 |
# Summary section
|
| 1522 |
if 'summary' in analysis_data and analysis_data['summary']:
|
| 1523 |
+
story.append(Paragraph("📋 Summary", self.styles['Heading3']))
|
| 1524 |
summary_text = analysis_data['summary']
|
| 1525 |
if isinstance(summary_text, str) and summary_text.strip():
|
| 1526 |
story.append(Paragraph(self._sanitize_text_persona(summary_text.strip()), self.styles['CustomBody']))
|
|
|
|
| 1528 |
|
| 1529 |
# Detailed Analysis section
|
| 1530 |
if 'detailed_analysis' in analysis_data and analysis_data['detailed_analysis']:
|
| 1531 |
+
story.append(Paragraph("📋 Detailed Analysis", self.styles['Heading3']))
|
| 1532 |
detailed_text = analysis_data['detailed_analysis']
|
| 1533 |
|
| 1534 |
if isinstance(detailed_text, dict):
|
|
|
|
| 1551 |
|
| 1552 |
# Tables section (consistent with Step 2)
|
| 1553 |
if 'tables' in analysis_data and analysis_data['tables']:
|
| 1554 |
+
story.append(Paragraph("📊 Data Tables", self.styles['Heading3']))
|
| 1555 |
tables = analysis_data['tables']
|
| 1556 |
if isinstance(tables, list):
|
| 1557 |
for table in tables:
|
|
|
|
| 1588 |
"""Create standard step PDF content for steps 2, 4, 5, 6"""
|
| 1589 |
# Summary section
|
| 1590 |
if 'summary' in analysis_data and analysis_data['summary']:
|
| 1591 |
+
story.append(Paragraph("📋 Summary", self.styles['Heading3']))
|
| 1592 |
summary_text = analysis_data['summary']
|
| 1593 |
if isinstance(summary_text, str) and summary_text.strip():
|
| 1594 |
# Apply comprehensive cleaning (same as analysis engine)
|
|
|
|
| 1600 |
|
| 1601 |
# Detailed Analysis section
|
| 1602 |
if 'detailed_analysis' in analysis_data and analysis_data['detailed_analysis']:
|
| 1603 |
+
story.append(Paragraph("📋 Detailed Analysis", self.styles['Heading3']))
|
| 1604 |
detailed_text = analysis_data['detailed_analysis']
|
| 1605 |
|
| 1606 |
if isinstance(detailed_text, dict):
|
|
|
|
| 1623 |
|
| 1624 |
# Tables section
|
| 1625 |
if 'tables' in analysis_data and analysis_data['tables']:
|
| 1626 |
+
story.append(Paragraph("📊 Data Tables", self.styles['Heading3']))
|
| 1627 |
tables = analysis_data['tables']
|
| 1628 |
if isinstance(tables, list):
|
| 1629 |
for table in tables:
|
|
|
|
| 3740 |
# If still no steps, create a comprehensive fallback message
|
| 3741 |
if not step_results:
|
| 3742 |
logger.warning("🔍 DEBUG - No step data found anywhere, creating comprehensive fallback content")
|
| 3743 |
+
story.append(Paragraph("Comprehensive Analysis Results:", self.styles['Heading2']))
|
| 3744 |
+
story.append(Paragraph("The analysis has been completed successfully. Below are the key findings and recommendations:", self.styles['Normal']))
|
| 3745 |
|
| 3746 |
# Add key findings if available
|
| 3747 |
if 'key_findings' in analysis_results:
|
| 3748 |
+
story.append(Paragraph("Key Findings:", self.styles['Heading3']))
|
| 3749 |
key_findings = analysis_results['key_findings']
|
| 3750 |
normalized_kf = []
|
| 3751 |
|
|
|
|
| 3775 |
|
| 3776 |
# Add summary if available
|
| 3777 |
if 'summary' in analysis_results:
|
| 3778 |
+
story.append(Paragraph("Summary:", self.styles['Heading3']))
|
| 3779 |
story.append(Paragraph(str(analysis_results['summary']), self.styles['CustomBody']))
|
| 3780 |
story.append(Spacer(1, 8))
|
| 3781 |
|
| 3782 |
# Add detailed analysis if available
|
| 3783 |
if 'detailed_analysis' in analysis_results:
|
| 3784 |
+
story.append(Paragraph("Detailed Analysis:", self.styles['Heading3']))
|
| 3785 |
story.append(Paragraph(str(analysis_results['detailed_analysis']), self.styles['CustomBody']))
|
| 3786 |
story.append(Spacer(1, 8))
|
| 3787 |
|
|
|
|
| 3843 |
|
| 3844 |
# Statistical Analysis (from enhanced LLM output)
|
| 3845 |
if 'statistical_analysis' in step and step['statistical_analysis']:
|
| 3846 |
+
story.append(Paragraph("Statistical Analysis:", self.styles['Heading3']))
|
| 3847 |
if isinstance(step['statistical_analysis'], dict):
|
| 3848 |
for key, value in step['statistical_analysis'].items():
|
| 3849 |
story.append(Paragraph(f"<b>{key.replace('_', ' ').title()}:</b> {value}", self.styles['CustomBody']))
|
|
|
|
| 3853 |
|
| 3854 |
# Issues Identified (crucial for farmers)
|
| 3855 |
if 'issues_identified' in step and step['issues_identified']:
|
| 3856 |
+
story.append(Paragraph("Issues Identified:", self.styles['Heading3']))
|
| 3857 |
for i, issue in enumerate(step['issues_identified'], 1):
|
| 3858 |
issue_text = f"<b>{i}.</b> {issue}"
|
| 3859 |
story.append(Paragraph(issue_text, self.styles['CustomBody']))
|
|
|
|
| 3861 |
|
| 3862 |
# Key Findings (from enhanced LLM output)
|
| 3863 |
if 'key_findings' in step and step['key_findings']:
|
| 3864 |
+
story.append(Paragraph("Key Findings:", self.styles['Heading3']))
|
| 3865 |
key_findings = step['key_findings']
|
| 3866 |
normalized_kf = []
|
| 3867 |
|
|
|
|
| 3894 |
|
| 3895 |
# Legacy recommendations (for backward compatibility)
|
| 3896 |
if 'recommendations' in step and step['recommendations']:
|
| 3897 |
+
story.append(Paragraph("Additional Recommendations:", self.styles['Heading3']))
|
| 3898 |
for i, rec in enumerate(step['recommendations'], 1):
|
| 3899 |
rec_text = f"<b>{i}.</b> {rec}"
|
| 3900 |
story.append(Paragraph(rec_text, self.styles['CustomBody']))
|
|
|
|
| 3911 |
# Explicitly list specific recommendations if provided
|
| 3912 |
specific_recs = step.get('specific_recommendations', [])
|
| 3913 |
if isinstance(specific_recs, list) and specific_recs:
|
| 3914 |
+
story.append(Paragraph("Specific Recommendations (Rates):", self.styles['Heading3']))
|
| 3915 |
for i, rec in enumerate(specific_recs, 1):
|
| 3916 |
story.append(Paragraph(f"{i}. {rec}", self.styles['CustomBody']))
|
| 3917 |
story.append(Spacer(1, 8))
|
|
|
|
| 3947 |
|
| 3948 |
if yield_chart is not None:
|
| 3949 |
logger.info("🔍 DEBUG Step 6 - Adding chart to story")
|
| 3950 |
+
story.append(Paragraph("📈 STEP 6 — Forecast Graph: 5-Year Yield Forecast & Projections", self.styles['Heading3']))
|
| 3951 |
story.append(Spacer(1, 8))
|
| 3952 |
story.append(yield_chart)
|
| 3953 |
story.append(Spacer(1, 12))
|
|
|
|
| 3955 |
else:
|
| 3956 |
logger.warning("❌ Step 6: Yield forecast chart is None")
|
| 3957 |
logger.info("🔍 DEBUG Step 6 - Chart is None, adding failure message")
|
| 3958 |
+
story.append(Paragraph("📈 STEP 6 — Forecast Graph: 5-Year Yield Forecast & Projections", self.styles['Heading3']))
|
| 3959 |
story.append(Spacer(1, 8))
|
| 3960 |
+
story.append(Paragraph("5-Year Yield Forecast (t/ha) - Chart generation failed", self.styles['Normal']))
|
| 3961 |
|
| 3962 |
except Exception as e:
|
| 3963 |
logger.error(f"❌ Step 6: Error adding yield forecast chart: {str(e)}")
|
| 3964 |
import traceback
|
| 3965 |
logger.error(f"Step 6 Full traceback: {traceback.format_exc()}")
|
| 3966 |
+
story.append(Paragraph("📈 STEP 6 — Forecast Graph: 5-Year Yield Forecast & Projections", self.styles['Heading3']))
|
| 3967 |
story.append(Spacer(1, 8))
|
| 3968 |
+
story.append(Paragraph("5-Year Yield Forecast (t/ha) - Chart generation error", self.styles['Normal']))
|
| 3969 |
|
| 3970 |
# Visualizations and Charts - ONLY Step 1 bar graphs; remove charts for Steps 2-6
|
| 3971 |
try:
|
|
|
|
| 6747 |
return story
|
| 6748 |
|
| 6749 |
# Economic Impact Forecast header
|
| 6750 |
+
story.append(Paragraph("Economic Impact Forecast", self.styles['Heading1']))
|
| 6751 |
story.append(Spacer(1, 12))
|
| 6752 |
|
| 6753 |
# Find economic forecast data from multiple possible locations
|
|
|
|
| 6801 |
|
| 6802 |
# Display basic information
|
| 6803 |
if current_yield > 0:
|
| 6804 |
+
story.append(Paragraph(f"<b>Current Yield:</b> {current_yield:.1f} tons/ha", self.styles['CustomBody']))
|
| 6805 |
else:
|
| 6806 |
+
story.append(Paragraph(f"<b>Current Yield:</b> Based on analysis results", self.styles['CustomBody']))
|
| 6807 |
|
| 6808 |
if land_size > 0:
|
| 6809 |
+
story.append(Paragraph(f"<b>Land Size:</b> {land_size:.1f} hectares", self.styles['CustomBody']))
|
| 6810 |
|
| 6811 |
# Add palm density information if available
|
| 6812 |
palm_density = econ.get('palm_density_per_hectare', 0)
|
| 6813 |
total_palms = econ.get('total_palms', 0)
|
| 6814 |
if palm_density > 0:
|
| 6815 |
+
story.append(Paragraph(f"<b>Palm Density:</b> {palm_density} palms/hectare", self.styles['CustomBody']))
|
| 6816 |
if total_palms > 0:
|
| 6817 |
+
story.append(Paragraph(f"<b>Total Palms:</b> {total_palms:,} palms", self.styles['CustomBody']))
|
| 6818 |
|
| 6819 |
# Use FFB price range for consistency
|
| 6820 |
ffb_price_range = econ.get('oil_palm_price_range_rm_per_tonne', 'RM 650-750')
|
| 6821 |
+
story.append(Paragraph(f"<b>FFB Price Range:</b> {ffb_price_range}/tonne", self.styles['CustomBody']))
|
| 6822 |
story.append(Spacer(1, 12))
|
| 6823 |
|
| 6824 |
# Remove Economic Forecast Assumptions section as requested
|
|
|
|
| 6831 |
# Fallback to Year-1 only display if no scenario data available
|
| 6832 |
year1 = econ.get('year_1', {}) if isinstance(econ, dict) else {}
|
| 6833 |
if year1:
|
| 6834 |
+
story.append(Paragraph("💹 Year-1 Economic Impact Forecast per Hectare", self.styles['Heading2']))
|
| 6835 |
story.append(Spacer(1, 6))
|
| 6836 |
# Build a simple key/value table from known fields, falling back gracefully
|
| 6837 |
keys = [
|
| 6838 |
+
('new_yield_tpha', 'New Yield (t/ha)'),
|
| 6839 |
+
('additional_yield_tpha', 'Additional Yield (t/ha)'),
|
| 6840 |
+
('additional_revenue_rm', 'Additional Revenue (RM)'),
|
| 6841 |
+
('cost_per_hectare_rm', 'Cost per Hectare (RM)'),
|
| 6842 |
# Prefer range if available; fall back to roi_percentage with cap note
|
| 6843 |
+
('roi_percentage_range', 'ROI (%)'),
|
| 6844 |
+
('payback_months', 'Payback (months)')
|
| 6845 |
]
|
| 6846 |
rows = []
|
| 6847 |
for k, label in keys:
|
|
|
|
| 6851 |
if k == 'roi_percentage_range' and isinstance(v, str):
|
| 6852 |
display_value = v
|
| 6853 |
elif 'roi_percentage' in k and isinstance(v, (int, float)):
|
| 6854 |
+
display_value = f"{60}% (Capped for realism - maximum sustainable ROI)" if v > 60 else f"{v:.1f}%"
|
| 6855 |
else:
|
| 6856 |
display_value = str(v)
|
| 6857 |
rows.append([label, display_value])
|
| 6858 |
if rows:
|
| 6859 |
+
table = self._create_table_with_proper_layout([["Metric", "Value"]] + rows, [self.content_width*0.5, self.content_width*0.5], font_size=9)
|
| 6860 |
if table:
|
| 6861 |
story.append(table)
|
| 6862 |
story.append(Spacer(1, 12))
|
|
|
|
| 6867 |
story.append(Paragraph("<i>Note: RM values are based on current market rates and typical plantation economics.</i>", self.styles['CustomBody']))
|
| 6868 |
else:
|
| 6869 |
# Create a basic economic forecast when data is not available
|
| 6870 |
+
story.append(Paragraph("Economic Impact Assessment", self.styles['Heading2']))
|
| 6871 |
story.append(Spacer(1, 8))
|
| 6872 |
|
| 6873 |
# Basic economic information
|
| 6874 |
+
story.append(Paragraph("<b>Current Yield:</b> Based on analysis results", self.styles['CustomBody']))
|
| 6875 |
+
story.append(Paragraph("<b>Projected Yield Improvement:</b> 15-25% with proper management", self.styles['CustomBody']))
|
| 6876 |
+
story.append(Paragraph("<b>Estimated ROI:</b> 200-300% over 3-5 years", self.styles['CustomBody']))
|
| 6877 |
story.append(Spacer(1, 12))
|
| 6878 |
|
| 6879 |
# Basic cost-benefit table
|
| 6880 |
+
story.append(Paragraph("Estimated Cost-Benefit Analysis", self.styles['Heading3']))
|
| 6881 |
story.append(Spacer(1, 8))
|
| 6882 |
|
| 6883 |
table_data = [
|
| 6884 |
+
['Investment Level', 'Total Investment (RM)', 'Expected Return (RM)', 'ROI (%)', 'Payback Period (Months)'],
|
| 6885 |
+
['Low Investment', '2,000 - 3,000', '8,000 - 12,000', '250-300', '24-36'],
|
| 6886 |
+
['Medium Investment', '4,000 - 6,000', '15,000 - 20,000', '275-350', '24-36'],
|
| 6887 |
+
['High Investment', '8,000 - 12,000', '25,000 - 35,000', '200-300', '36-48']
|
| 6888 |
]
|
| 6889 |
|
| 6890 |
col_widths = [
|
|
|
|
| 6910 |
story = []
|
| 6911 |
|
| 6912 |
# 5-Year Yield Forecast header
|
| 6913 |
+
story.append(Paragraph("5-Year Yield Forecast", self.styles['Heading1']))
|
| 6914 |
story.append(Spacer(1, 12))
|
| 6915 |
|
| 6916 |
# Find yield forecast data from multiple possible locations
|
|
|
|
| 7123 |
story = []
|
| 7124 |
|
| 7125 |
# Conclusion header
|
| 7126 |
+
story.append(Paragraph("Detailed Conclusion", self.styles['Heading1']))
|
| 7127 |
story.append(Spacer(1, 12))
|
| 7128 |
|
| 7129 |
# Extract key data for personalized conclusion
|
|
|
|
| 7135 |
conclusion_parts = []
|
| 7136 |
|
| 7137 |
# Analysis overview
|
| 7138 |
+
conclusion_parts.append("""
|
| 7139 |
+
<b>Analysis Overview:</b><br/>
|
| 7140 |
+
This comprehensive agricultural analysis has systematically evaluated your oil palm plantation's current nutritional status and identified critical areas for improvement. The step-by-step analysis reveals specific challenges and opportunities that directly impact your plantation's productivity and profitability.
|
| 7141 |
""")
|
| 7142 |
|
| 7143 |
# Key findings summary
|
| 7144 |
if step_analysis:
|
| 7145 |
+
conclusion_parts.append("""
|
| 7146 |
+
<b>Key Findings Summary:</b><br/>
|
| 7147 |
+
The analysis has identified several critical factors affecting your plantation's performance. These findings provide a clear roadmap for targeted interventions that will maximize your return on investment while ensuring sustainable agricultural practices.
|
| 7148 |
""")
|
| 7149 |
|
| 7150 |
# Economic impact
|
| 7151 |
if economic_forecast:
|
| 7152 |
+
conclusion_parts.append("""
|
| 7153 |
+
<b>Economic Impact Assessment:</b><br/>
|
| 7154 |
+
The economic analysis demonstrates significant potential for improved profitability through strategic interventions. The investment scenarios presented show clear pathways to enhanced yields and increased revenue, with medium investment approaches typically offering the optimal balance between cost-effectiveness and yield improvement.
|
| 7155 |
""")
|
| 7156 |
|
| 7157 |
# Yield projections
|
| 7158 |
if yield_forecast:
|
| 7159 |
+
conclusion_parts.append("""
|
| 7160 |
+
<b>5-Year Yield Projections:</b><br/>
|
| 7161 |
+
The yield forecast analysis provides a detailed roadmap for sustainable growth over the next five years. These projections are based on realistic investment scenarios and account for seasonal variations, market conditions, and implementation timelines. The forecast demonstrates the potential for substantial yield improvements with proper management and targeted interventions.
|
| 7162 |
""")
|
| 7163 |
|
| 7164 |
# Implementation recommendations
|
| 7165 |
+
conclusion_parts.append("""
|
| 7166 |
+
<b>Implementation Strategy:</b><br/>
|
| 7167 |
+
Successful implementation of these recommendations requires a phased approach, beginning with high-priority interventions and gradually expanding to comprehensive management practices. Regular monitoring and adaptive management will be essential to achieving the projected outcomes and ensuring long-term sustainability.
|
| 7168 |
""")
|
| 7169 |
|
| 7170 |
# Long-term outlook
|
| 7171 |
+
conclusion_parts.append("""
|
| 7172 |
+
<b>Long-term Outlook:</b><br/>
|
| 7173 |
+
The analysis indicates strong potential for sustained productivity improvements and enhanced profitability. By following the recommended strategies and maintaining consistent monitoring practices, your plantation can achieve significant yield increases while contributing to sustainable agricultural intensification goals. The 5-year projections provide a clear vision for long-term success and continued growth.
|
| 7174 |
""")
|
| 7175 |
|
| 7176 |
# Combine all conclusion parts
|
|
|
|
| 7180 |
story.append(Spacer(1, 20))
|
| 7181 |
|
| 7182 |
# Add final summary paragraph
|
| 7183 |
+
final_summary = """
|
| 7184 |
+
<b>Final Summary:</b><br/>
|
| 7185 |
+
This analysis provides a comprehensive foundation for optimizing your oil palm plantation's performance. The combination of detailed nutritional assessment, economic analysis, and yield projections offers a clear path forward for achieving improved productivity and profitability. Implementation of the recommended strategies will position your plantation for sustainable success and long-term growth.
|
| 7186 |
"""
|
| 7187 |
|
| 7188 |
story.append(Paragraph(final_summary, self.styles['CustomBody']))
|
|
|
|
| 7195 |
story = []
|
| 7196 |
|
| 7197 |
# Results header
|
| 7198 |
+
story.append(Paragraph("Analysis Results", self.styles['Heading1']))
|
| 7199 |
story.append(Spacer(1, 12))
|
| 7200 |
|
| 7201 |
# Create simplified metadata table without debug information
|
|
|
|
| 7208 |
formatted_time = timestamp.strftime("%Y-%m-%d")
|
| 7209 |
else:
|
| 7210 |
formatted_time = str(timestamp)[:10] # Just the date part
|
| 7211 |
+
metadata_data.append(['Analysis Date', formatted_time])
|
| 7212 |
|
| 7213 |
# Report Types only
|
| 7214 |
report_types = analysis_data.get('report_types', ['soil', 'leaf'])
|
| 7215 |
if report_types:
|
| 7216 |
+
metadata_data.append(['Report Types', ', '.join(report_types)])
|
| 7217 |
|
| 7218 |
if metadata_data:
|
| 7219 |
metadata_table = self._create_table_with_proper_layout(metadata_data)
|
|
|
|
| 7237 |
story = []
|
| 7238 |
|
| 7239 |
# Raw Data header
|
| 7240 |
+
story.append(Paragraph("Raw Analysis Data", self.styles['Heading1']))
|
| 7241 |
story.append(Spacer(1, 12))
|
| 7242 |
|
| 7243 |
# Get raw data from analysis
|
|
|
|
| 7247 |
|
| 7248 |
# Soil parameters table
|
| 7249 |
if soil_params:
|
| 7250 |
+
story.append(Paragraph("Soil Analysis Parameters", self.styles['Heading2']))
|
| 7251 |
story.append(Spacer(1, 8))
|
| 7252 |
|
| 7253 |
# Create soil parameters table
|
| 7254 |
+
soil_data = [['Parameter', 'Average', 'Min', 'Max', 'Unit']]
|
| 7255 |
for param, data in soil_params.items():
|
| 7256 |
if isinstance(data, dict) and 'average' in data:
|
| 7257 |
unit = data.get('unit', '')
|
|
|
|
| 7280 |
|
| 7281 |
# Leaf parameters table
|
| 7282 |
if leaf_params:
|
| 7283 |
+
story.append(Paragraph("Leaf Analysis Parameters", self.styles['Heading2']))
|
| 7284 |
story.append(Spacer(1, 8))
|
| 7285 |
|
| 7286 |
# Create leaf parameters table
|
| 7287 |
+
leaf_data = [['Parameter', 'Average', 'Min', 'Max', 'Unit']]
|
| 7288 |
for param, data in leaf_params.items():
|
| 7289 |
if isinstance(data, dict) and 'average' in data:
|
| 7290 |
unit = data.get('unit', '')
|
|
|
|
| 7313 |
story.append(Spacer(1, 12))
|
| 7314 |
|
| 7315 |
if not soil_params and not leaf_params:
|
| 7316 |
+
story.append(Paragraph("No raw data available for this analysis.", self.styles['CustomBody']))
|
| 7317 |
|
| 7318 |
story.append(Spacer(1, 20))
|
| 7319 |
return story
|
|
|
|
| 7323 |
story = []
|
| 7324 |
|
| 7325 |
# References header
|
| 7326 |
+
story.append(Paragraph("References", self.styles['Heading1']))
|
| 7327 |
story.append(Spacer(1, 12))
|
| 7328 |
|
| 7329 |
# Get references from analysis data
|
|
|
|
| 7333 |
total_refs = len(all_references.get('database_references', []))
|
| 7334 |
|
| 7335 |
if total_refs > 0:
|
| 7336 |
+
story.append(Paragraph(f"<b>Total References Found:</b> {total_refs}", self.styles['CustomBody']))
|
| 7337 |
story.append(Spacer(1, 12))
|
| 7338 |
|
| 7339 |
# Database references only
|
| 7340 |
if all_references['database_references']:
|
| 7341 |
+
story.append(Paragraph("Database References", self.styles['Heading2']))
|
| 7342 |
story.append(Spacer(1, 8))
|
| 7343 |
|
| 7344 |
for i, ref in enumerate(all_references['database_references'], 1):
|
|
|
|
| 9513 |
if 'tables' in data and data['tables']:
|
| 9514 |
tables = data['tables']
|
| 9515 |
if isinstance(tables, list):
|
| 9516 |
+
story.append(Paragraph("📊 Data Tables", self.styles['Heading2']))
|
| 9517 |
story.append(Spacer(1, 8))
|
| 9518 |
for i, table_data in enumerate(tables, 1):
|
| 9519 |
if not isinstance(table_data, dict):
|
|
|
|
| 9730 |
if para_text:
|
| 9731 |
elements.append(Paragraph(self._sanitize_text_persona(para_text), self.styles['CustomBody']))
|
| 9732 |
|
| 9733 |
+
return elements
|
utils/translations.py
CHANGED
|
@@ -340,51 +340,6 @@ TRANSLATIONS = {
|
|
| 340 |
'pdf_no_leaf_data': 'No leaf nutrient data available',
|
| 341 |
'pdf_raw_soil_data': 'Raw Soil Sample Data',
|
| 342 |
'pdf_raw_leaf_data': 'Raw Leaf Sample Data',
|
| 343 |
-
'pdf_analysis_results': 'Analysis Results',
|
| 344 |
-
'pdf_data_tables': 'Data Tables',
|
| 345 |
-
'pdf_analysis_date': 'Analysis Date',
|
| 346 |
-
'pdf_report_types': 'Report Types',
|
| 347 |
-
'pdf_comprehensive_analysis_results': 'Comprehensive Analysis Results',
|
| 348 |
-
'pdf_summary': 'Summary',
|
| 349 |
-
'pdf_detailed_analysis': 'Detailed Analysis',
|
| 350 |
-
'pdf_statistical_analysis': 'Statistical Analysis',
|
| 351 |
-
'pdf_issues_identified': 'Issues Identified',
|
| 352 |
-
'pdf_additional_recommendations': 'Additional Recommendations',
|
| 353 |
-
'pdf_specific_recommendations': 'Specific Recommendations (Rates)',
|
| 354 |
-
'pdf_economic_impact_forecast': 'Economic Impact Forecast',
|
| 355 |
-
'pdf_current_yield': 'Current Yield',
|
| 356 |
-
'pdf_land_size': 'Land Size',
|
| 357 |
-
'pdf_palm_density': 'Palm Density',
|
| 358 |
-
'pdf_total_palms': 'Total Palms',
|
| 359 |
-
'pdf_ffb_price_range': 'FFB Price Range',
|
| 360 |
-
'pdf_year_1_economic_impact': 'Year-1 Economic Impact Forecast per Hectare',
|
| 361 |
-
'pdf_metric': 'Metric',
|
| 362 |
-
'pdf_value_label': 'Value',
|
| 363 |
-
'pdf_estimated_cost_benefit': 'Estimated Cost-Benefit Analysis',
|
| 364 |
-
'pdf_investment_level': 'Investment Level',
|
| 365 |
-
'pdf_total_investment': 'Total Investment (RM)',
|
| 366 |
-
'pdf_expected_return': 'Expected Return (RM)',
|
| 367 |
-
'pdf_roi_percent': 'ROI (%)',
|
| 368 |
-
'pdf_payback_period': 'Payback Period (Months)',
|
| 369 |
-
'pdf_5_year_yield_forecast': '5-Year Yield Forecast',
|
| 370 |
-
'pdf_detailed_conclusion': 'Detailed Conclusion',
|
| 371 |
-
'pdf_analysis_overview': 'Analysis Overview',
|
| 372 |
-
'pdf_key_findings_summary': 'Key Findings Summary',
|
| 373 |
-
'pdf_economic_impact_assessment': 'Economic Impact Assessment',
|
| 374 |
-
'pdf_5_year_yield_projections': '5-Year Yield Projections',
|
| 375 |
-
'pdf_implementation_strategy': 'Implementation Strategy',
|
| 376 |
-
'pdf_long_term_outlook': 'Long-term Outlook',
|
| 377 |
-
'pdf_final_summary': 'Final Summary',
|
| 378 |
-
'pdf_references': 'References',
|
| 379 |
-
'pdf_total_references_found': 'Total References Found',
|
| 380 |
-
'pdf_database_references': 'Database References',
|
| 381 |
-
'pdf_raw_analysis_data': 'Raw Analysis Data',
|
| 382 |
-
'pdf_soil_analysis_parameters': 'Soil Analysis Parameters',
|
| 383 |
-
'pdf_leaf_analysis_parameters': 'Leaf Analysis Parameters',
|
| 384 |
-
'pdf_no_raw_data': 'No raw data available for this analysis.',
|
| 385 |
-
'pdf_data_analysis_results': 'Data Analysis Results',
|
| 386 |
-
'pdf_forecast_graph': 'Forecast Graph',
|
| 387 |
-
'pdf_5_year_yield_forecast_projections': '5-Year Yield Forecast & Projections',
|
| 388 |
},
|
| 389 |
'ms': {
|
| 390 |
# Common
|
|
@@ -718,74 +673,6 @@ TRANSLATIONS = {
|
|
| 718 |
'pdf_no_leaf_data': 'Tiada data nutrien daun tersedia',
|
| 719 |
'pdf_raw_soil_data': 'Data Sampel Tanah Mentah',
|
| 720 |
'pdf_raw_leaf_data': 'Data Sampel Daun Mentah',
|
| 721 |
-
'pdf_analysis_results': 'Hasil Analisis',
|
| 722 |
-
'pdf_executive_summary_fallback': 'Ringkasan eksekutif tidak dapat dijana daripada data analisis.',
|
| 723 |
-
'pdf_summary_error': 'Ringkasan tidak dapat dijana disebabkan masalah teknikal.',
|
| 724 |
-
'pdf_analysis_completed': 'Analisis telah selesai dengan jayanya. Berikut adalah penemuan utama dan cadangan:',
|
| 725 |
-
'pdf_based_on_analysis': 'Berdasarkan hasil analisis',
|
| 726 |
-
'pdf_projected_yield_improvement': 'Peningkatan Hasil Dijangka',
|
| 727 |
-
'pdf_with_proper_management': 'dengan pengurusan yang betul',
|
| 728 |
-
'pdf_estimated_roi': 'ROI Anggaran',
|
| 729 |
-
'pdf_over_years': 'lebih 3-5 tahun',
|
| 730 |
-
'pdf_new_yield': 'Hasil Baru (t/ha)',
|
| 731 |
-
'pdf_additional_yield': 'Hasil Tambahan (t/ha)',
|
| 732 |
-
'pdf_additional_revenue': 'Pendapatan Tambahan (RM)',
|
| 733 |
-
'pdf_cost_per_hectare': 'Kos Setiap Hektar (RM)',
|
| 734 |
-
'pdf_payback_months': 'Pulangan Modal (bulan)',
|
| 735 |
-
'pdf_roi_capped': 'Dihadkan untuk realisme - ROI maksimum yang mampan',
|
| 736 |
-
'pdf_chart_generation_failed': 'Penjanaan carta gagal',
|
| 737 |
-
'pdf_chart_generation_error': 'Ralat penjanaan carta',
|
| 738 |
-
'pdf_conclusion_overview_text': 'Analisis pertanian komprehensif ini telah menilai secara sistematik status pemakanan semasa ladang kelapa sawit anda dan mengenal pasti kawasan kritikal untuk penambahbaikan. Analisis langkah demi langkah mendedahkan cabaran dan peluang khusus yang memberi kesan langsung kepada produktiviti dan keuntungan ladang anda.',
|
| 739 |
-
'pdf_conclusion_findings_text': 'Analisis telah mengenal pasti beberapa faktor kritikal yang mempengaruhi prestasi ladang anda. Penemuan ini menyediakan peta jalan yang jelas untuk intervensi sasaran yang akan memaksimumkan pulangan pelaburan anda sambil memastikan amalan pertanian yang mampan.',
|
| 740 |
-
'pdf_conclusion_economic_text': 'Analisis ekonomi menunjukkan potensi yang ketara untuk peningkatan keuntungan melalui intervensi strategik. Senario pelaburan yang dibentangkan menunjukkan laluan yang jelas untuk peningkatan hasil dan peningkatan pendapatan, dengan pendekatan pelaburan sederhana biasanya menawarkan keseimbangan optimum antara keberkesanan kos dan peningkatan hasil.',
|
| 741 |
-
'pdf_conclusion_yield_text': 'Analisis ramalan hasil menyediakan peta jalan terperinci untuk pertumbuhan mampan selama lima tahun akan datang. Unjuran ini berdasarkan senario pelaburan yang realistik dan mengambil kira variasi bermusim, keadaan pasaran, dan garis masa pelaksanaan. Ramalan menunjukkan potensi untuk peningkatan hasil yang ketara dengan pengurusan yang betul dan intervensi sasaran.',
|
| 742 |
-
'pdf_conclusion_implementation_text': 'Pelaksanaan yang berjaya bagi cadangan ini memerlukan pendekatan berperingkat, bermula dengan intervensi keutamaan tinggi dan secara beransur-ansur berkembang kepada amalan pengurusan komprehensif. Pemantauan berkala dan pengurusan adaptif akan penting untuk mencapai hasil yang diunjurkan dan memastikan kemampanan jangka panjang.',
|
| 743 |
-
'pdf_conclusion_longterm_text': 'Analisis menunjukkan potensi yang kuat untuk peningkatan produktiviti yang berterusan dan peningkatan keuntungan. Dengan mengikuti strategi yang disyorkan dan mengekalkan amalan pemantauan yang konsisten, ladang anda boleh mencapai peningkatan hasil yang ketara sambil menyumbang kepada matlamat intensifikasi pertanian mampan. Unjuran 5 tahun menyediakan visi yang jelas untuk kejayaan jangka panjang dan pertumbuhan berterusan.',
|
| 744 |
-
'pdf_conclusion_final_text': 'Analisis ini menyediakan asas komprehensif untuk mengoptimumkan prestasi ladang kelapa sawit anda. Gabungan penilaian pemakanan terperinci, analisis ekonomi, dan unjuran hasil menawarkan laluan yang jelas ke hadapan untuk mencapai peningkatan produktiviti dan keuntungan. Pelaksanaan strategi yang disyorkan akan meletakkan ladang anda untuk kejayaan mampan dan pertumbuhan jangka panjang.',
|
| 745 |
-
'pdf_data_tables': 'Jadual Data',
|
| 746 |
-
'pdf_analysis_date': 'Tarikh Analisis',
|
| 747 |
-
'pdf_report_types': 'Jenis Laporan',
|
| 748 |
-
'pdf_comprehensive_analysis_results': 'Hasil Analisis Komprehensif',
|
| 749 |
-
'pdf_summary': 'Ringkasan',
|
| 750 |
-
'pdf_detailed_analysis': 'Analisis Terperinci',
|
| 751 |
-
'pdf_statistical_analysis': 'Analisis Statistik',
|
| 752 |
-
'pdf_issues_identified': 'Isu yang Dikenal pasti',
|
| 753 |
-
'pdf_additional_recommendations': 'Cadangan Tambahan',
|
| 754 |
-
'pdf_specific_recommendations': 'Cadangan Spesifik (Kadar)',
|
| 755 |
-
'pdf_economic_impact_forecast': 'Ramalan Kesan Ekonomi',
|
| 756 |
-
'pdf_current_yield': 'Hasil Semasa',
|
| 757 |
-
'pdf_land_size': 'Saiz Tanah',
|
| 758 |
-
'pdf_palm_density': 'Kepadatan Sawit',
|
| 759 |
-
'pdf_total_palms': 'Jumlah Pokok Sawit',
|
| 760 |
-
'pdf_ffb_price_range': 'Julat Harga FFB',
|
| 761 |
-
'pdf_year_1_economic_impact': 'Ramalan Kesan Ekonomi Tahun-1 Setiap Hektar',
|
| 762 |
-
'pdf_metric': 'Metrik',
|
| 763 |
-
'pdf_value_label': 'Nilai',
|
| 764 |
-
'pdf_estimated_cost_benefit': 'Analisis Kos-Faedah Anggaran',
|
| 765 |
-
'pdf_investment_level': 'Tahap Pelaburan',
|
| 766 |
-
'pdf_total_investment': 'Jumlah Pelaburan (RM)',
|
| 767 |
-
'pdf_expected_return': 'Pulangan Dijangka (RM)',
|
| 768 |
-
'pdf_roi_percent': 'ROI (%)',
|
| 769 |
-
'pdf_payback_period': 'Tempoh Pulangan Modal (Bulan)',
|
| 770 |
-
'pdf_5_year_yield_forecast': 'Ramalan Hasil 5 Tahun',
|
| 771 |
-
'pdf_detailed_conclusion': 'Kesimpulan Terperinci',
|
| 772 |
-
'pdf_analysis_overview': 'Gambaran Keseluruhan Analisis',
|
| 773 |
-
'pdf_key_findings_summary': 'Ringkasan Penemuan Utama',
|
| 774 |
-
'pdf_economic_impact_assessment': 'Penilaian Kesan Ekonomi',
|
| 775 |
-
'pdf_5_year_yield_projections': 'Unjuran Hasil 5 Tahun',
|
| 776 |
-
'pdf_implementation_strategy': 'Strategi Pelaksanaan',
|
| 777 |
-
'pdf_long_term_outlook': 'Prospek Jangka Panjang',
|
| 778 |
-
'pdf_final_summary': 'Ringkasan Akhir',
|
| 779 |
-
'pdf_references': 'Rujukan',
|
| 780 |
-
'pdf_total_references_found': 'Jumlah Rujukan Dijumpai',
|
| 781 |
-
'pdf_database_references': 'Rujukan Pangkalan Data',
|
| 782 |
-
'pdf_raw_analysis_data': 'Data Analisis Mentah',
|
| 783 |
-
'pdf_soil_analysis_parameters': 'Parameter Analisis Tanah',
|
| 784 |
-
'pdf_leaf_analysis_parameters': 'Parameter Analisis Daun',
|
| 785 |
-
'pdf_no_raw_data': 'Tiada data mentah tersedia untuk analisis ini.',
|
| 786 |
-
'pdf_data_analysis_results': 'Hasil Analisis Data',
|
| 787 |
-
'pdf_forecast_graph': 'Graf Ramalan',
|
| 788 |
-
'pdf_5_year_yield_forecast_projections': 'Ramalan & Unjuran Hasil 5 Tahun',
|
| 789 |
}
|
| 790 |
}
|
| 791 |
|
|
@@ -862,4 +749,3 @@ def translate(key: str, default: str = None, **kwargs) -> str:
|
|
| 862 |
def t(key: str, default: str = None, **kwargs) -> str:
|
| 863 |
"""Short alias for translate"""
|
| 864 |
return translate(key, default, **kwargs)
|
| 865 |
-
|
|
|
|
| 340 |
'pdf_no_leaf_data': 'No leaf nutrient data available',
|
| 341 |
'pdf_raw_soil_data': 'Raw Soil Sample Data',
|
| 342 |
'pdf_raw_leaf_data': 'Raw Leaf Sample Data',
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 343 |
},
|
| 344 |
'ms': {
|
| 345 |
# Common
|
|
|
|
| 673 |
'pdf_no_leaf_data': 'Tiada data nutrien daun tersedia',
|
| 674 |
'pdf_raw_soil_data': 'Data Sampel Tanah Mentah',
|
| 675 |
'pdf_raw_leaf_data': 'Data Sampel Daun Mentah',
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 676 |
}
|
| 677 |
}
|
| 678 |
|
|
|
|
| 749 |
def t(key: str, default: str = None, **kwargs) -> str:
|
| 750 |
"""Short alias for translate"""
|
| 751 |
return translate(key, default, **kwargs)
|
|
|