asif-coder commited on
Commit
1063fc9
ยท
verified ยท
1 Parent(s): 3d03b35

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +49 -65
app.py CHANGED
@@ -1,95 +1,79 @@
1
  import gradio as gr
2
  import pandas as pd
3
- import numpy as np
4
  from fpdf import FPDF
5
  import datetime
6
- import os
7
 
8
- # --- 2026 MARKET DATA CONFIG ---
9
- CONFIG = {
10
- "panel_pkr_watt": 32,
11
- "sun_hours": 5.2,
12
- "grid_rate": 55.0,
13
- "buyback_rate": 11.0,
14
- "li_battery_kwh": 48000,
15
- "markup": 0.15,
16
  }
17
 
18
- # --- MODULE: BANK API INTEGRATION ---
19
- def fetch_bank_rates():
20
- """
21
- Simulated API call to Bank Alfalah/JS Bank for 2026 Solar Financing.
22
- In production, use: requests.get('https://api.bankalfalah.com/rates')
23
- """
24
- return {"interest_rate": 0.14, "tenure_months": 60, "bank_name": "Bank Alfalah"}
25
-
26
- # --- MODULE: PDF GENERATOR ---
27
- def generate_report(load, size, cost, emi, roi):
28
  pdf = FPDF()
29
  pdf.add_page()
30
- pdf.set_font("Arial", 'B', 16)
31
- pdf.cell(200, 10, "Solar Solution Report - Pakistan 2026", ln=True, align='C')
32
 
33
- pdf.set_font("Arial", size=12)
34
  pdf.ln(10)
35
- pdf.cell(200, 10, f"Date: {datetime.datetime.now().strftime('%Y-%m-%d')}", ln=True)
36
- pdf.cell(200, 10, f"Total Connected Load: {load} Watts", ln=True)
37
- pdf.cell(200, 10, f"Recommended System Size: {size} kW", ln=True)
38
- pdf.cell(200, 10, f"Estimated Total Investment: PKR {cost:,}", ln=True)
39
- pdf.cell(200, 10, f"Monthly EMI Plan: PKR {emi:,}/month", ln=True)
40
- pdf.cell(200, 10, f"Estimated Payback Period: {roi} Years", ln=True)
41
 
42
- report_path = "Solar_Report_PK.pdf"
43
  pdf.output(report_path)
44
  return report_path
45
 
46
- # --- CORE LOGIC ---
47
- def solar_engine(app_selection, counts, sys_type, backup_hrs):
48
- # Load math (20% losses included)
49
- watts_map = {"AC": 1500, "Fan": 80, "Fridge": 250, "Lights": 12}
50
- total_watts = sum([watts_map[k] for k in app_selection])
51
-
52
- daily_units = (total_watts * 10) / 1000 # Avg 10h usage
53
- sys_size = round((daily_units / CONFIG["sun_hours"]) * 1.2, 1)
54
-
55
- panel_cost = sys_size * 1000 * CONFIG["panel_pkr_watt"]
56
- battery_cost = (daily_units * (backup_hrs/24) * CONFIG["li_battery_kwh"])
57
-
58
- total_cost = int((panel_cost + battery_cost + 200000) * (1 + CONFIG["markup"]))
59
 
60
  # Financials
61
- bank = fetch_bank_rates()
62
- p = total_cost * 0.8
63
- r = bank["interest_rate"] / 12
64
- n = bank["tenure_months"]
65
- emi = int(p * (r * (1+r)**n) / ((1+r)**n - 1))
66
 
67
- roi = round(total_cost / (daily_units * 365 * 45), 1)
 
 
 
 
 
 
 
 
 
 
 
 
68
 
69
- pdf_file = generate_report(total_watts, sys_size, total_cost, emi, roi)
70
 
71
- summary = f"""### ๐Ÿ“‹ System Insights
72
- - **Size:** {sys_size} kW
73
- - **Total Cost:** PKR {total_cost:,}
74
- - **EMI:** PKR {emi:,}/mo ({bank['bank_name']})
 
75
  """
76
  return summary, pdf_file
77
 
78
- # --- GRADIO UI ---
79
- with gr.Blocks(theme=gr.themes.Default()) as demo:
80
- gr.Markdown("# โ˜€๏ธ Solar Consultant Pro (Pakistan)")
81
-
82
  with gr.Row():
83
  with gr.Column():
84
- apps = gr.CheckboxGroup(["AC", "Fan", "Fridge", "Lights"], label="Appliances")
85
- sys = gr.Dropdown(["On-Grid", "Hybrid", "Off-Grid"], label="System Type", value="Hybrid")
86
- bkp = gr.Slider(0, 12, value=4, label="Battery Backup (Hours)")
87
- btn = gr.Button("Analyze & Generate PDF", variant="primary")
88
-
 
89
  with gr.Column():
90
  out_md = gr.Markdown()
91
- out_pdf = gr.File(label="Download Full Report")
92
 
93
- btn.click(solar_engine, inputs=[apps, gr.State(1), sys, bkp], outputs=[out_md, out_pdf])
94
 
95
  demo.launch()
 
1
  import gradio as gr
2
  import pandas as pd
 
3
  from fpdf import FPDF
4
  import datetime
 
5
 
6
+ # --- 2026 DYNAMIC MARKET DATA ---
7
+ MARKET_DATA = {
8
+ "panel_pkr_w": 32,
9
+ "sun_hrs": 5.2,
10
+ "bank_rate": 0.14, # Simulated Alfalah Rate
11
+ "installation": 0.15
 
 
12
  }
13
 
14
+ def generate_pdf(data):
 
 
 
 
 
 
 
 
 
15
  pdf = FPDF()
16
  pdf.add_page()
17
+ pdf.set_font("Helvetica", 'B', 16)
18
+ pdf.cell(0, 10, "Solar Feasibility Report - Pakistan 2026", center=True, new_x="LMARGIN", new_y="NEXT")
19
 
20
+ pdf.set_font("Helvetica", size=12)
21
  pdf.ln(10)
22
+ for key, value in data.items():
23
+ pdf.cell(0, 10, f"{key}: {value}", new_x="LMARGIN", new_y="NEXT")
 
 
 
 
24
 
25
+ report_path = "Solar_Insights_Report.pdf"
26
  pdf.output(report_path)
27
  return report_path
28
 
29
+ def solar_calculator(ac_count, fan_count, light_count, sys_type):
30
+ # Engineering Math
31
+ load = (ac_count * 1500) + (fan_count * 80) + (light_count * 12)
32
+ daily_units = (load * 8) / 1000
33
+ sys_kw = round((daily_units / MARKET_DATA["sun_hrs"]) * 1.2, 2)
 
 
 
 
 
 
 
 
34
 
35
  # Financials
36
+ cost = int((sys_kw * 1000 * MARKET_DATA["panel_pkr_w"] + 250000) * (1 + MARKET_DATA["installation"]))
 
 
 
 
37
 
38
+ # Bank EMI Calculation (P * r * (1+r)^n / ((1+r)^n - 1))
39
+ p = cost * 0.7 # 30% Downpayment
40
+ r = MARKET_DATA["bank_rate"] / 12
41
+ n = 60
42
+ emi = int(p * (r * (1+r)**n) / ((1+r)**n - 1))
43
+
44
+ results = {
45
+ "Total Load (W)": load,
46
+ "System Size (kW)": sys_kw,
47
+ "Total Cost (PKR)": f"{cost:,}",
48
+ "Monthly EMI (PKR)": f"{emi:,}",
49
+ "Date Generated": datetime.datetime.now().strftime("%Y-%m-%d")
50
+ }
51
 
52
+ pdf_file = generate_pdf(results)
53
 
54
+ summary = f"""
55
+ ## ๐Ÿ“Š Estimation Results
56
+ - **Recommended System:** {sys_kw} kW {sys_type}
57
+ - **Estimated Investment:** PKR {cost:,}
58
+ - **Financing:** PKR {emi:,}/month via Bank Alfalah
59
  """
60
  return summary, pdf_file
61
 
62
+ # --- UI DESIGN ---
63
+ with gr.Blocks(title="Solar PK Pro") as demo:
64
+ gr.Markdown("# โ˜€๏ธ SolarExpert Pakistan 2.0")
 
65
  with gr.Row():
66
  with gr.Column():
67
+ ac = gr.Number(label="Inverter ACs (1.5 Ton)", value=1)
68
+ fans = gr.Number(label="Ceiling Fans", value=4)
69
+ lights = gr.Number(label="LED Lights", value=10)
70
+ stype = gr.Dropdown(["On-Grid", "Hybrid"], label="System Architecture", value="Hybrid")
71
+ calc_btn = gr.Button("Calculate & Generate Report", variant="primary")
72
+
73
  with gr.Column():
74
  out_md = gr.Markdown()
75
+ out_file = gr.File(label="Download PDF Insights")
76
 
77
+ calc_btn.click(solar_calculator, inputs=[ac, fans, lights, stype], outputs=[out_md, out_file])
78
 
79
  demo.launch()