GIGAParviz commited on
Commit
e6b76e7
·
verified ·
1 Parent(s): 84ecc31

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +154 -154
app.py CHANGED
@@ -1,155 +1,155 @@
1
- from flask import Flask, render_template, request, redirect, url_for, send_file, flash, jsonify
2
- import os
3
- import traceback
4
- from pathlib import Path
5
- import json
6
- import pandas as pd
7
-
8
- app = Flask(__name__)
9
- app.secret_key = os.urandom(24)
10
-
11
- try:
12
- import main as project_main
13
- except Exception as e:
14
- project_main = None
15
- import_error = traceback.format_exc()
16
- else:
17
- import_error = None
18
-
19
- RESULTS_CSV = Path("results_flask.csv")
20
-
21
- def safe_update_dict_from_json(orig_dict, json_text):
22
- if not json_text or not json_text.strip():
23
- return orig_dict
24
- try:
25
- new = json.loads(json_text)
26
- if not isinstance(new, dict):
27
- return orig_dict
28
- d = orig_dict.copy()
29
- d.update(new)
30
- return d
31
- except Exception:
32
- return orig_dict
33
-
34
- @app.route("/", methods=["GET"])
35
- def index():
36
- if project_main is None:
37
- return render_template("index.html", import_error=import_error, project=None)
38
- techs = list(project_main.TECHNOLOGY_DATA.keys())
39
- defaults = {
40
- "inflation": project_main.INFLATION_RATE,
41
- "tax": project_main.TAX_RATE,
42
- "years": project_main.PROJECT_YEARS,
43
- "cap_min": project_main.OPTIMIZATION_SPACE['capacity_kta'][0],
44
- "cap_max": project_main.OPTIMIZATION_SPACE['capacity_kta'][1],
45
- "export_mix": project_main.OPTIMIZATION_SPACE['export_market_mix'][0],
46
- }
47
- return render_template("index.html", import_error=None, project=project_main, techs=techs, defaults=defaults)
48
-
49
- @app.route("/run", methods=["POST"])
50
- def run():
51
- if project_main is None:
52
- flash("خطا: فایل main.py بارگزاری نشد. لطفاً لاگ را بررسی کنید.", "danger")
53
- return redirect(url_for("index"))
54
- try:
55
- inflation_rate = float(request.form.get("inflation", project_main.INFLATION_RATE))
56
- tax_rate = float(request.form.get("tax", project_main.TAX_RATE))
57
- project_years = int(request.form.get("years", project_main.PROJECT_YEARS))
58
- capacity_min = float(request.form.get("cap_min", project_main.OPTIMIZATION_SPACE['capacity_kta'][0]))
59
- capacity_max = float(request.form.get("cap_max", project_main.OPTIMIZATION_SPACE['capacity_kta'][1]))
60
- technology = request.form.get("technology", list(project_main.TECHNOLOGY_DATA.keys())[0])
61
- export_mix = float(request.form.get("export_mix", project_main.OPTIMIZATION_SPACE['export_market_mix'][0]))
62
- sell_byproducts = request.form.get("sell_byproducts") == "on"
63
- tech_json = request.form.get("tech_json", "")
64
- prices_json = request.form.get("prices_json", "")
65
- except Exception as e:
66
- flash("خطا در خواندن ورودی‌ها: " + str(e), "danger")
67
- return redirect(url_for("index"))
68
-
69
- try:
70
- project_main.INFLATION_RATE = inflation_rate
71
- project_main.TAX_RATE = tax_rate
72
- project_main.PROJECT_YEARS = project_years
73
-
74
- project_main.OPTIMIZATION_SPACE['capacity_kta'] = (capacity_min, capacity_max)
75
- if technology not in project_main.OPTIMIZATION_SPACE.get('technology', []):
76
- project_main.OPTIMIZATION_SPACE['technology'] = [technology]
77
- low = max(0.0, export_mix - 0.05)
78
- high = min(1.0, export_mix + 0.05)
79
- if low == high:
80
- high = min(1.0, high + 0.01)
81
- project_main.OPTIMIZATION_SPACE['export_market_mix'] = (low, high)
82
- project_main.OPTIMIZATION_SPACE['sell_byproducts'] = [bool(sell_byproducts)]
83
-
84
- project_main.TECHNOLOGY_DATA = safe_update_dict_from_json(project_main.TECHNOLOGY_DATA, tech_json)
85
- project_main.PRODUCT_PRICES_USD_PER_TON = safe_update_dict_from_json(project_main.PRODUCT_PRICES_USD_PER_TON, prices_json)
86
- except Exception as e:
87
- flash("خطا در اعمال پارامترها: " + str(e), "danger")
88
- return redirect(url_for("index"))
89
-
90
- try:
91
- flash("محاسبات شروع شد — صبر کنید تا عملیات به پایان برسد...", "info")
92
- results = project_main.run_optimizations_without_ml()
93
- df_results = pd.DataFrame(results).sort_values(by="irr", ascending=False).reset_index(drop=True)
94
- df_results = df_results.round(2)
95
-
96
- df_results.to_csv(RESULTS_CSV, index=False, encoding='utf-8-sig')
97
-
98
- try:
99
- project_main.display_and_save_results(df_results)
100
- project_main.create_kpi_comparison_dashboard(df_results)
101
- except Exception:
102
- pass
103
-
104
- if not df_results.empty:
105
- best = df_results.iloc[0]
106
- top_kpis = {
107
- "irr": round(float(best['irr']), 2),
108
- "annual_profit_M": round(float(best['annual_profit'])/1_000_000, 2),
109
- "capex_M": round(float(best['total_capex'])/1_000_000, 2),
110
- "payback": round(float(best['payback_period']), 2)
111
- }
112
- else:
113
- top_kpis = None
114
-
115
- charts_data = df_results.to_dict(orient="records")
116
-
117
- flash("محاسبات با موفقیت تکمیل شد.", "success")
118
-
119
- kpi_img = Path("static/images/kpi_dashboard.png") if Path("static/images/kpi_dashboard.png").exists() else None
120
- tornado_img = Path("static/images/sensitivity_analysis_tornado.png") if Path("static/images/sensitivity_analysis_tornado.png").exists() else None
121
-
122
- return render_template(
123
- "index.html",
124
- project=project_main,
125
- techs=list(project_main.TECHNOLOGY_DATA.keys()),
126
- defaults={"inflation": project_main.INFLATION_RATE, "tax": project_main.TAX_RATE},
127
- table_html = df_results.to_html(
128
- classes='table table-striped table-dark',
129
- index=False,
130
- justify='center',
131
- float_format=lambda x: f"{x:.2f}"
132
- ),
133
- top_kpis=top_kpis,
134
- charts_json=json.dumps(charts_data, default=str),
135
- kpi_img="images/kpi_dashboard.png" if kpi_img else None,
136
- tornado_img="images/sensitivity_analysis_tornado.png" if tornado_img else None
137
- )
138
-
139
- except Exception as e:
140
- tb = traceback.format_exc()
141
- flash("خطا در اجرای الگوریتم‌ها. لاگ: " + str(e), "danger")
142
- return render_template("index.html", import_error=tb, project=project_main)
143
-
144
- @app.route("/download")
145
- def download_results():
146
- if RESULTS_CSV.exists():
147
- return send_file(str(RESULTS_CSV), as_attachment=True)
148
- flash("فایل نتایج آماده نیست.", "warning")
149
- return redirect(url_for("index"))
150
-
151
- if __name__ == "__main__":
152
- app.run(debug=True)
153
-
154
-
155
 
 
1
+ from flask import Flask, render_template, request, redirect, url_for, send_file, flash, jsonify
2
+ import os
3
+ import traceback
4
+ from pathlib import Path
5
+ import json
6
+ import pandas as pd
7
+
8
+ app = Flask(__name__)
9
+ app.secret_key = os.urandom(24)
10
+
11
+ try:
12
+ import main as project_main
13
+ except Exception as e:
14
+ project_main = None
15
+ import_error = traceback.format_exc()
16
+ else:
17
+ import_error = None
18
+
19
+ RESULTS_CSV = Path("results_flask.csv")
20
+
21
+ def safe_update_dict_from_json(orig_dict, json_text):
22
+ if not json_text or not json_text.strip():
23
+ return orig_dict
24
+ try:
25
+ new = json.loads(json_text)
26
+ if not isinstance(new, dict):
27
+ return orig_dict
28
+ d = orig_dict.copy()
29
+ d.update(new)
30
+ return d
31
+ except Exception:
32
+ return orig_dict
33
+
34
+ @app.route("/", methods=["GET"])
35
+ def index():
36
+ if project_main is None:
37
+ return render_template("index.html", import_error=import_error, project=None)
38
+ techs = list(project_main.TECHNOLOGY_DATA.keys())
39
+ defaults = {
40
+ "inflation": project_main.INFLATION_RATE,
41
+ "tax": project_main.TAX_RATE,
42
+ "years": project_main.PROJECT_YEARS,
43
+ "cap_min": project_main.OPTIMIZATION_SPACE['capacity_kta'][0],
44
+ "cap_max": project_main.OPTIMIZATION_SPACE['capacity_kta'][1],
45
+ "export_mix": project_main.OPTIMIZATION_SPACE['export_market_mix'][0],
46
+ }
47
+ return render_template("index.html", import_error=None, project=project_main, techs=techs, defaults=defaults)
48
+
49
+ @app.route("/run", methods=["POST"])
50
+ def run():
51
+ if project_main is None:
52
+ flash("خطا: فایل main.py بارگزاری نشد. لطفاً لاگ را بررسی کنید.", "danger")
53
+ return redirect(url_for("index"))
54
+ try:
55
+ inflation_rate = float(request.form.get("inflation", project_main.INFLATION_RATE))
56
+ tax_rate = float(request.form.get("tax", project_main.TAX_RATE))
57
+ project_years = int(request.form.get("years", project_main.PROJECT_YEARS))
58
+ capacity_min = float(request.form.get("cap_min", project_main.OPTIMIZATION_SPACE['capacity_kta'][0]))
59
+ capacity_max = float(request.form.get("cap_max", project_main.OPTIMIZATION_SPACE['capacity_kta'][1]))
60
+ technology = request.form.get("technology", list(project_main.TECHNOLOGY_DATA.keys())[0])
61
+ export_mix = float(request.form.get("export_mix", project_main.OPTIMIZATION_SPACE['export_market_mix'][0]))
62
+ sell_byproducts = request.form.get("sell_byproducts") == "on"
63
+ tech_json = request.form.get("tech_json", "")
64
+ prices_json = request.form.get("prices_json", "")
65
+ except Exception as e:
66
+ flash("خطا در خواندن ورودی‌ها: " + str(e), "danger")
67
+ return redirect(url_for("index"))
68
+
69
+ try:
70
+ project_main.INFLATION_RATE = inflation_rate
71
+ project_main.TAX_RATE = tax_rate
72
+ project_main.PROJECT_YEARS = project_years
73
+
74
+ project_main.OPTIMIZATION_SPACE['capacity_kta'] = (capacity_min, capacity_max)
75
+ if technology not in project_main.OPTIMIZATION_SPACE.get('technology', []):
76
+ project_main.OPTIMIZATION_SPACE['technology'] = [technology]
77
+ low = max(0.0, export_mix - 0.05)
78
+ high = min(1.0, export_mix + 0.05)
79
+ if low == high:
80
+ high = min(1.0, high + 0.01)
81
+ project_main.OPTIMIZATION_SPACE['export_market_mix'] = (low, high)
82
+ project_main.OPTIMIZATION_SPACE['sell_byproducts'] = [bool(sell_byproducts)]
83
+
84
+ project_main.TECHNOLOGY_DATA = safe_update_dict_from_json(project_main.TECHNOLOGY_DATA, tech_json)
85
+ project_main.PRODUCT_PRICES_USD_PER_TON = safe_update_dict_from_json(project_main.PRODUCT_PRICES_USD_PER_TON, prices_json)
86
+ except Exception as e:
87
+ flash("خطا در اعمال پارامترها: " + str(e), "danger")
88
+ return redirect(url_for("index"))
89
+
90
+ try:
91
+ flash("محاسبات شروع شد — صبر کنید تا عملیات به پایان برسد...", "info")
92
+ results = project_main.run_optimizations_without_ml()
93
+ df_results = pd.DataFrame(results).sort_values(by="irr", ascending=False).reset_index(drop=True)
94
+ df_results = df_results.round(2)
95
+
96
+ df_results.to_csv(RESULTS_CSV, index=False, encoding='utf-8-sig')
97
+
98
+ try:
99
+ project_main.display_and_save_results(df_results)
100
+ project_main.create_kpi_comparison_dashboard(df_results)
101
+ except Exception:
102
+ pass
103
+
104
+ if not df_results.empty:
105
+ best = df_results.iloc[0]
106
+ top_kpis = {
107
+ "irr": round(float(best['irr']), 2),
108
+ "annual_profit_M": round(float(best['annual_profit'])/1_000_000, 2),
109
+ "capex_M": round(float(best['total_capex'])/1_000_000, 2),
110
+ "payback": round(float(best['payback_period']), 2)
111
+ }
112
+ else:
113
+ top_kpis = None
114
+
115
+ charts_data = df_results.to_dict(orient="records")
116
+
117
+ flash("محاسبات با موفقیت تکمیل شد.", "success")
118
+
119
+ kpi_img = Path("static/images/kpi_dashboard.png") if Path("static/images/kpi_dashboard.png").exists() else None
120
+ tornado_img = Path("static/images/sensitivity_analysis_tornado.png") if Path("static/images/sensitivity_analysis_tornado.png").exists() else None
121
+
122
+ return render_template(
123
+ "index.html",
124
+ project=project_main,
125
+ techs=list(project_main.TECHNOLOGY_DATA.keys()),
126
+ defaults={"inflation": project_main.INFLATION_RATE, "tax": project_main.TAX_RATE},
127
+ table_html = df_results.to_html(
128
+ classes='table table-striped table-dark',
129
+ index=False,
130
+ justify='center',
131
+ float_format=lambda x: f"{x:.2f}"
132
+ ),
133
+ top_kpis=top_kpis,
134
+ charts_json=json.dumps(charts_data, default=str),
135
+ kpi_img="images/kpi_dashboard.png" if kpi_img else None,
136
+ tornado_img="images/sensitivity_analysis_tornado.png" if tornado_img else None
137
+ )
138
+
139
+ except Exception as e:
140
+ tb = traceback.format_exc()
141
+ flash("خطا در اجرای الگوریتم‌ها. لاگ: " + str(e), "danger")
142
+ return render_template("index.html", import_error=tb, project=project_main)
143
+
144
+ @app.route("/download")
145
+ def download_results():
146
+ if RESULTS_CSV.exists():
147
+ return send_file(str(RESULTS_CSV), as_attachment=True)
148
+ flash("فایل نتایج آماده نیست.", "warning")
149
+ return redirect(url_for("index"))
150
+
151
+ if __name__ == "__main__":
152
+ app.run(host="0.0.0.0", port=int(os.environ.get("PORT", 7860)))
153
+
154
+
155