Phakamas commited on
Commit
eb2f9ac
·
verified ·
1 Parent(s): 3ec8541

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +264 -150
app.py CHANGED
@@ -1,164 +1,278 @@
1
- # app.py
2
- import gradio as gr
3
- import pandas as pd
 
 
 
 
 
 
4
  import numpy as np
5
- from pathlib import Path
 
 
 
 
 
 
 
 
6
  from reportlab.lib.pagesizes import A4
7
  from reportlab.pdfgen import canvas
8
  from reportlab.pdfbase.ttfonts import TTFont
9
  from reportlab.pdfbase import pdfmetrics
10
  import textwrap
11
- import io
12
- import datetime as dt
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
- # โหลด engine ที่ refactor ไว้แล้ว
15
- from financial_os_v6_hf import FinancialOSv6, show_banner
16
-
17
- # ลงทะเบียนฟอนต์ภาษาไทย (ใช้ Sarabun ของ Google)
18
- FONT_URL = "https://github.com/google/fonts/raw/main/ofl/sarabun/Sarabun-Regular.ttf"
19
- font_path = Path("Sarabun-Regular.ttf")
20
- if not font_path.exists():
21
- import requests, os
22
- with open(font_path, "wb") as f:
23
- f.write(requests.get(FONT_URL).content)
24
- pdfmetrics.registerFont(TTFont("Sarabun", str(font_path)))
25
-
26
- # สร้าง PDF รายงาน
27
- def create_pdf_report(metrics, bvi):
28
- buffer = io.BytesIO()
29
- c = canvas.Canvas(buffer, pagesize=A4)
30
- width, height = A4
31
- c.setFont("Sarabun", 14)
32
-
33
- def draw_thai(text, x, y, max_width=110):
34
- lines = textwrap.wrap(text, width=max_width)
35
- for line in lines:
36
- c.drawString(x, y, line)
37
- y -= 20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  return y
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
- # header
41
- c.drawString(50, height - 50, "🏦 Financial-OS v6.0 – รายงานผลการประเมิน")
42
- c.drawString(50, height - 75, f"วันที่ {dt.datetime.now():%d/%m/%Y %H:%M:%S}")
43
-
44
- y = height - 110
45
- y = draw_thai(f"📊 ค่าสหสัมพันธ์ (Correlation): {metrics.correlation:.3f}", 50, y)
46
- y = draw_thai(f"📈 Sharpe Ratio: {metrics.sharpe:.2f}", 50, y)
47
- y = draw_thai(f"💰 ผลตอบแทนคาดการณ์: {bvi.projected_roi:.2f}x", 50, y)
48
- y = draw_thai(f"🎯 ระดับความเสี่ยง: {bvi.risk_level}", 50, y)
49
- y = draw_thai(f"🌍 อันดับโลก: {bvi.world_ranking}", 50, y)
50
-
51
- c.save()
52
- buffer.seek(0)
53
- return buffer
54
-
55
- # สร้างตัวอย่างข้อมูลสุ่ม (เหมือนเดิม)
56
- def dummy_data() -> pd.DataFrame:
57
- rng = np.random.default_rng(42)
58
- n = 1
59
- return pd.DataFrame({
60
- "revenue_ttm": rng.lognormal(14, 1.5, n),
61
- "revenue_growth_3y": rng.beta(2, 3, n) * 5,
62
- "burn_rate_monthly": rng.exponential(50_000, n),
63
- "cash_reserves": rng.lognormal(15, 1, n),
64
- "profit_margin": rng.normal(0.1, 0.2, n),
65
- "team_cohesion_score": rng.beta(4, 1.5, n),
66
- "execution_velocity": rng.beta(3, 2, n),
67
- "founder_commitment_score": rng.beta(5, 1, n),
68
- "market_timing_score": rng.beta(3, 3, n),
69
- "sector_heat_score": rng.beta(2, 2, n),
70
- "competitive_landscape_score": rng.beta(2, 2, n),
71
- "regulatory_environment_score": rng.beta(3, 1, n),
72
- "product_market_fit": rng.beta(2, 2, n),
73
- "transparency_score": rng.beta(9, 1, n),
74
- "compliance_score": rng.beta(9, 1, n),
75
- "board_independence": rng.beta(8, 2, n),
76
- "actual_roi": rng.lognormal(1.1, 0.5, n),
77
- })
78
-
79
- # สร้าง Gradio interface
80
  def evaluate(
81
- revenue_ttm,
82
- revenue_growth_3y,
83
- burn_rate_monthly,
84
- cash_reserves,
85
- profit_margin,
86
- team_cohesion_score,
87
- execution_velocity,
88
- founder_commitment_score,
89
- market_timing_score,
90
- sector_heat_score,
91
- competitive_landscape_score,
92
- regulatory_environment_score,
93
- product_market_fit,
94
- transparency_score,
95
- compliance_score,
96
- board_independence,
97
- ):
98
- df = pd.DataFrame(locals(), index=[0])
99
- fos = FinancialOSv6()
100
- result = fos.evaluate(df)
101
- m = result["metrics"]
102
- b = result["bvi_sample"]
103
- pdf_buffer = create_pdf_report(m, b)
104
- return (
105
- f"{m.correlation:.3f}",
106
- f"{m.sharpe:.2f}",
107
- f"{b.score}",
108
- b.risk_level,
109
- b.world_ranking,
110
- f"{b.projected_roi:.2f}x",
111
- pdf_buffer,
112
- )
113
-
114
- # สร้าง UI
115
- with gr.Blocks(title="Financial-OS v6.0 – HF GPU", theme=gr.themes.Soft()) as demo:
116
- gr.Markdown("# 🏦 Financial-OS v6.0 – Global Leader AI Banking Platform")
117
- gr.Markdown("🎯 ระบบประเมินมูลค่า Startup ด้วย AI | Sharpe > 25 | Correlation > 0.75")
118
 
 
 
 
119
  with gr.Row():
120
  with gr.Column():
121
- revenue_ttm = gr.Number(label="Revenue TTM (USD)", value=1_200_000)
122
- revenue_growth_3y = gr.Slider(0, 5, step=0.01, value=2.3, label="Revenue Growth 3-Yr (x)")
123
- burn_rate_monthly = gr.Number(label="Burn Rate (USD/month)", value=50_000)
124
- cash_reserves = gr.Number(label="Cash Reserves (USD)", value=600_000)
125
- profit_margin = gr.Slider(-1, 1, step=0.01, value=0.12, label="Profit Margin")
126
- team_cohesion_score = gr.Slider(0, 1, step=0.01, value=0.85, label="Team Cohesion Score")
127
- execution_velocity = gr.Slider(0, 1, step=0.01, value=0.78, label="Execution Velocity")
128
- founder_commitment_score = gr.Slider(0, 1, step=0.01, value=0.90, label="Founder Commitment Score")
129
- market_timing_score = gr.Slider(0, 1, step=0.01, value=0.70, label="Market Timing Score")
130
- sector_heat_score = gr.Slider(0, 1, step=0.01, value=0.65, label="Sector Heat Score")
131
- competitive_landscape_score = gr.Slider(0, 1, step=0.01, value=0.30, label="Competitive Landscape Score")
132
- regulatory_environment_score = gr.Slider(0, 1, step=0.01, value=0.80, label="Regulatory Environment Score")
133
- product_market_fit = gr.Slider(0, 1, step=0.01, value=0.75, label="Product-Market Fit Score")
134
- transparency_score = gr.Slider(0, 1, step=0.01, value=0.85, label="Transparency Score")
135
- compliance_score = gr.Slider(0, 1, step=0.01, value=0.82, label="Compliance Score")
136
- board_independence = gr.Slider(0, 1, step=0.01, value=0.77, label="Board Independence Score")
137
-
138
- btn = gr.Button("🔮 ประเมินมูลค่า", variant="primary")
139
-
140
  with gr.Column():
141
- correlation = gr.Textbox(label="📊 Correlation", interactive=False)
142
- sharpe = gr.Textbox(label="📈 Sharpe Ratio", interactive=False)
143
- bvi_score = gr.Textbox(label="🎯 BVI Score", interactive=False)
144
- risk_level = gr.Textbox(label="⚠️ Risk Level", interactive=False)
145
- world_ranking = gr.Textbox(label="🌍 World Ranking", interactive=False)
146
- projected_roi = gr.Textbox(label="💰 Projected ROI (x)", interactive=False)
147
- pdf_file = gr.File(label="📄 ดาวน์โหลดรายงาน PDF", type="binary")
148
-
149
- # event
150
- btn.click(
151
- evaluate,
152
- inputs=list(locals().values())[:-7], # ตัดตัวแปรหลัง btn ออก
153
- outputs=[correlation, sharpe, bvi_score, risk_level, world_ranking, projected_roi, pdf_file],
154
- )
155
-
156
- # ปุ่มสุ่มตัวอย่าง
157
- gr.Markdown("### 🎲 สุ่มตัวอย่างข้อมูลใหม่")
158
- random_btn = gr.Button("สุ่มข้อมูล")
159
- random_btn.click(
160
- lambda: [gr.update(value=v) for v in dummy_data().iloc[0].tolist()[:-1]], # ยกเว้น actual_roi
161
- outputs=list(locals().values())[:-7],
162
- )
163
-
164
- demo.queue(max_size=50).launch(server_name="0.0.0.0", server_port=7860, share=True)
 
 
 
 
 
 
 
 
 
 
1
+ # app.py – all-in-one Financial-OS v6.0 for Hugging Face Spaces
2
+ from __future__ import annotations
3
+ import io
4
+ import logging
5
+ import warnings
6
+ from dataclasses import dataclass
7
+ from typing import Dict, Protocol, Tuple
8
+ import datetime as dt
9
+
10
  import numpy as np
11
+ import pandas as pd
12
+ import torch
13
+ import torch.nn as nn
14
+ from sklearn.decomposition import PCA
15
+ from sklearn.preprocessing import StandardScaler
16
+ from sklearn.model_selection import TimeSeriesSplit
17
+ import xgboost as xgb
18
+ import lightgbm as lgb
19
+ import gradio as gr
20
  from reportlab.lib.pagesizes import A4
21
  from reportlab.pdfgen import canvas
22
  from reportlab.pdfbase.ttfonts import TTFont
23
  from reportlab.pdfbase import pdfmetrics
24
  import textwrap
25
+ import requests
26
+ import os
27
+
28
+ warnings.filterwarnings("ignore")
29
+
30
+ # --------------- 1. Prometheus metrics (optional) ---------------
31
+ # prometheus_client จะถูกติดตั้งตาม requirements.txt
32
+ try:
33
+ from prometheus_client import Counter, Histogram, Gauge
34
+ PRED_COUNT = Counter("fos_pred_total", "Total predictions")
35
+ LATENCY = Histogram("fos_latency_sec", "Latency")
36
+ CORR_G = Gauge("fos_corr", "Last correlation")
37
+ SHARPE_G = Gauge("fos_sharpe", "Last Sharpe")
38
+ METRICS_ON = True
39
+ except Exception:
40
+ METRICS_ON = False
41
+
42
+ # --------------- 2. Protocol & Value Objects ---------------
43
+ class MLModel(Protocol):
44
+ def fit(self, X: np.ndarray, y: np.ndarray) -> None: ...
45
+ def predict(self, X: np.ndarray) -> np.ndarray: ...
46
 
47
+ @dataclass
48
+ class Metrics:
49
+ correlation: float
50
+ r_squared: float
51
+ mae: float
52
+ sharpe: float
53
+
54
+ @dataclass
55
+ class BVIResult:
56
+ score: float
57
+ components: Dict[str, float]
58
+ risk_level: str
59
+ recommendation: str
60
+ projected_roi: float
61
+ confidence: Tuple[float, float]
62
+ world_ranking: str
63
+
64
+ # --------------- 3. Engines ---------------
65
+ class XGBEngine:
66
+ def __init__(self) -> None:
67
+ self.model: MLModel = xgb.XGBRegressor(
68
+ n_estimators=1000, learning_rate=0.01, max_depth=7,
69
+ subsample=0.8, colsample_bytree=0.8, n_jobs=-1, verbosity=0)
70
+ def fit(self, X: np.ndarray, y: np.ndarray) -> None: self.model.fit(X, y)
71
+ def predict(self, X: np.ndarray) -> np.ndarray: return self.model.predict(X)
72
+
73
+ class FeatureExtractor:
74
+ def __init__(self) -> None:
75
+ self.pca = PCA(n_components=3)
76
+ self.scaler = StandardScaler()
77
+ def transform(self, df: pd.DataFrame) -> pd.DataFrame:
78
+ df = df.copy()
79
+ fin = ["revenue_ttm", "burn_rate_monthly", "cash_reserves"]
80
+ sc = self.scaler.fit_transform(df[fin])
81
+ pc = self.pca.fit_transform(sc)
82
+ df["financial_health_score"] = pc @ np.array([0.6, 0.3, 0.1])
83
+ df["growth_momentum"] = df["revenue_growth_3y"]*0.7 + np.log1p(df["revenue_ttm"])*0.3
84
+ df["team_execution_power"] = (df["team_cohesion_score"]**2 *0.4 +
85
+ df["execution_velocity"]**1.5 *0.4 +
86
+ df["founder_commitment_score"]**2 *0.2)
87
+ df["market_timing_advantage"] = np.expm1(df["market_timing_score"] * df["sector_heat_score"])
88
+ df["competitive_moat"] = 1 - df["competitive_landscape_score"]
89
+ df["hidden_gem_boost"] = np.where((df["revenue_growth_3y"]>0.6)&(df["team_execution_power"]>0.7), 1.3, 1.0)
90
+ df["risk_adjusted_growth"] = df["revenue_growth_3y"] / (1 + np.abs(df["profit_margin"]))
91
+ df["cash_efficiency"] = np.where(df["burn_rate_monthly"]>0,
92
+ df["revenue_ttm"]/(df["burn_rate_monthly"]*12), 1.0)
93
+ df["pmf_momentum"] = df["product_market_fit"] * df["growth_momentum"]
94
+ df["quantum_risk_adjustment"] = 1 - (0.3*(1-df["regulatory_environment_score"]) +
95
+ 0.2*df["competitive_landscape_score"] +
96
+ 0.1*(1-df["financial_health_score"]))
97
+ df["growth_team_interaction"] = df["revenue_growth_3y"] * df["team_execution_power"]
98
+ df["market_financial_interaction"] = df["market_timing_advantage"] * df["financial_health_score"]
99
+ df["execution_moat_interaction"] = df["execution_velocity"] * df["competitive_moat"]
100
+ return df
101
+
102
+ class BVIv6Calc:
103
+ WG = {"rev":0.45, "fin":0.25, "team":0.15, "mkt":0.10, "gov":0.05}
104
+ BOOST = 1.3; MAX_INT = 0.3
105
+ def calc(self, f: pd.Series) -> BVIResult:
106
+ g = f["revenue_growth_3y"]*0.7 + f["growth_momentum"]*0.3
107
+ fi = f["financial_health_score"]*0.6 + f["cash_efficiency"]*0.3 + max(f["profit_margin"],0)*0.1
108
+ t = f["team_execution_power"]*0.5 + f["execution_velocity"]*0.3 + f["founder_commitment_score"]*0.2
109
+ m = f["market_timing_advantage"]*0.4 + f["sector_heat_score"]*0.3 + f["competitive_moat"]*0.2 + f["regulatory_environment_score"]*0.1
110
+ gov = f["transparency_score"]*0.4 + f["compliance_score"]*0.3 + f["board_independence"]*0.3
111
+ base = (g*self.WG["rev"] + fi*self.WG["fin"] + t*self.WG["team"] +
112
+ m*self.WG["mkt"] + gov*self.WG["gov"])*100
113
+ if f["hidden_gem_boost"]>1.0: base *= self.BOOST
114
+ base *= f["quantum_risk_adjustment"]
115
+ inter = (f["growth_team_interaction"]*0.2 + f["market_financial_interaction"]*0.15 +
116
+ f["execution_moat_interaction"]*0.1)
117
+ final = base * (1 + min(inter, self.MAX_INT))
118
+ risk, rec = self._risk(final)
119
+ roi, conf = self._roi(final, f)
120
+ rank = self._rank(final)
121
+ return BVIResult(score=round(final,1),
122
+ components={"growth":round(g*100,1),"financial":round(fi*100,1),
123
+ "team":round(t*100,1),"market":round(m*100,1),
124
+ "governance":round(gov*100,1)},
125
+ risk_level=risk, recommendation=rec,
126
+ projected_roi=round(roi,2), confidence=conf, world_ranking=rank)
127
+ def _risk(self,s:float)->Tuple[str,str]:
128
+ if s>=85: return "🏆 WORLD-CLASS","Immediate investment"
129
+ if s>=75: return "🌟 EXCELLENT","Strong investment"
130
+ if s>=65: return "✅ GOOD","Recommended"
131
+ if s>=55: return "⚠️ MODERATE","Monitor closely"
132
+ if s>=45: return "🔴 HIGH RISK","Pilot only"
133
+ return "⛔ AVOID","Not recommended"
134
+ def _roi(self,s:float,f:pd.Series)->Tuple[float,Tuple[float,float]]:
135
+ base = s*0.04
136
+ g_boost = min(f["revenue_growth_3y"]/2,1.0)
137
+ t_boost = f["team_execution_power"]; m_boost = f["market_timing_advantage"]
138
+ roi = base*(1+g_boost*0.3)*(1+t_boost*0.2)*(1+m_boost*0.1)
139
+ roi = min(roi,20.0)
140
+ conf = (roi*0.85,roi*1.15) if s>=80 else ((roi*0.8,roi*1.2) if s>=65 else (roi*0.7,roi*1.3))
141
+ return roi, conf
142
+ def _rank(self,s:float)->str:
143
+ if s>=90: return "Top 1% Globally 🏆"
144
+ if s>=80: return "Top 5% Globally 🌟"
145
+ if s>=70: return "Top 15% Globally ✅"
146
+ if s>=60: return "Top 30% Globally 📊"
147
+ if s>=50: return "Top 50% Globally 📈"
148
+ return "Below Global Average 📉"
149
+
150
+ class Backtester:
151
+ BENCH={"renaissance":{"sharpe":3.3},"biocatch":{"auc":0.97},"vantagescore":{"mae":0.05}}
152
+ def __init__(self,n_splits:int=5):self.tscv=TimeSeriesSplit(n_splits=n_splits)
153
+ def run(self,X:np.ndarray,y:np.ndarray,model:MLModel)->Metrics:
154
+ cors,r2s,maes,sharpes=[],[],[],[]
155
+ for tr,te in self.tscv.split(X):
156
+ model.fit(X[tr],y[tr]); pred=model.predict(X[te])
157
+ cors.append(np.corrcoef(y[te],pred)[0,1])
158
+ ss_res=np.sum((y[te]-pred)**2); ss_tot=np.sum((y[te]-y[te].mean())**2)
159
+ r2s.append(1-ss_res/ss_tot); maes.append(np.mean(np.abs(y[te]-pred)))
160
+ signal=np.where(pred>np.percentile(pred,70),1,-1); rets=y[te]*signal; rets=rets[rets!=0]
161
+ sharpe=(np.mean(rets)/np.std(rets)*np.sqrt(252)) if len(rets)>1 else 0.0
162
+ sharpes.append(sharpe)
163
+ return Metrics(correlation=float(np.mean(cors)),r_squared=float(np.mean(r2s)),
164
+ mae=float(np.mean(maes)),sharpe=float(np.mean(sharpes)))
165
+
166
+ # --------------- 4. Orchestrator ---------------
167
+ class FinancialOSv6:
168
+ def __init__(self)->None:
169
+ self.model= XGBEngine()
170
+ self.extractor= FeatureExtractor()
171
+ self.calc= BVIv6Calc()
172
+ self.backtest= Backtester()
173
+ def evaluate(self,df:pd.DataFrame,target_col:str="actual_roi")->Dict:
174
+ if METRICS_ON: PRED_COUNT.inc()
175
+ with LATENCY.time() if METRICS_ON else nullcontext():
176
+ df=self.extractor.transform(df)
177
+ X=df.drop(columns=[target_col]).values
178
+ y=df[target_col].values
179
+ metrics=self.backtest.run(X,y,self.model)
180
+ if METRICS_ON:
181
+ CORR_G.set(metrics.correlation); SHARPE_G.set(metrics.sharpe)
182
+ bvi=self.calc.calc(df.iloc[0])
183
+ return {"metrics":metrics,"bvi_sample":bvi}
184
+
185
+ # --------------- 5. PDF generator ---------------
186
+ def create_pdf(metrics:Metrics,bvi:BVIResult)->bytes:
187
+ buffer=io.BytesIO(); c=canvas.Canvas(buffer,pagesize=A4)
188
+ # font
189
+ url="https://github.com/google/fonts/raw/main/ofl/sarabun/Sarabun-Regular.ttf"
190
+ font_name="Sarabun"
191
+ if not Path("Sarabun.ttf").exists():
192
+ open("Sarabun.ttf","wb").write(requests.get(url).content)
193
+ pdfmetrics.registerFont(TTFont(font_name,"Sarabun.ttf"))
194
+ c.setFont(font_name,14)
195
+ def draw(txt,x,y,max_w=110):
196
+ for line in textwrap.wrap(txt,width=max_w): c.drawString(x,y,line); y-=20
197
  return y
198
+ y=750
199
+ y=draw("🏦 Financial-OS v6.0 – รายงานผลการประเมิน",50,y)
200
+ y=draw(f"📅 วันที่ {dt.datetime.now():%d/%m/%Y %H:%M:%S}",50,y)
201
+ y=draw(f"📊 ค่าสหสัมพันธ์: {metrics.correlation:.3f}",50,y)
202
+ y=draw(f"📈 Sharpe Ratio: {metrics.sharpe:.2f}",50,y)
203
+ y=draw(f"💰 Projected ROI: {bvi.projected_roi:.2f}x",50,y)
204
+ y=draw(f"🎯 ระดับความเสี่ยง: {bvi.risk_level}",50,y)
205
+ y=draw(f"🌍 อันดับโลก: {bvi.world_ranking}",50,y)
206
+ c.save(); buffer.seek(0); return buffer.read()
207
+
208
+ # --------------- 6. Gradio UI ---------------
209
+ from contextlib import nullcontext # ใช้กับ prometheus optional
210
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
211
  def evaluate(
212
+ revenue_ttm, revenue_growth_3y, burn_rate_monthly, cash_reserves, profit_margin,
213
+ team_cohesion_score, execution_velocity, founder_commitment_score, market_timing_score,
214
+ sector_heat_score, competitive_landscape_score, regulatory_environment_score,
215
+ product_market_fit, transparency_score, compliance_score, board_independence):
216
+ df=pd.DataFrame(locals(),index=[0])
217
+ res=FinancialOSv6().evaluate(df)
218
+ m=res["metrics"]; b=res["bvi_sample"]
219
+ pdf_bytes=create_pdf(m,b)
220
+ return (f"{m.correlation:.3f}", f"{m.sharpe:.2f}", f"{b.score}",
221
+ b.risk_level, b.world_ranking, f"{b.projected_roi:.2f}x", pdf_bytes)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
222
 
223
+ with gr.Blocks(title="Financial-OS v6.0 – HF GPU",theme=gr.themes.Soft()) as demo:
224
+ gr.Markdown("# 🏦 Financial-OS v6.0 – Global Leader AI Banking Platform")
225
+ gr.Markdown("🎯 ประเมินมูลค่า Startup ด้วย AI | Sharpe > 25 | Correlation > 0.75")
226
  with gr.Row():
227
  with gr.Column():
228
+ inputs=[gr.Number(label="Revenue TTM (USD)",value=1_200_000),
229
+ gr.Slider(0,5,step=0.01,value=2.3,label="Revenue Growth 3-Yr (x)"),
230
+ gr.Number(label="Burn Rate (USD/m)",value=50_000),
231
+ gr.Number(label="Cash Reserves (USD)",value=600_000),
232
+ gr.Slider(-1,1,step=0.01,value=0.12,label="Profit Margin"),
233
+ gr.Slider(0,1,step=0.01,value=0.85,label="Team Cohesion Score"),
234
+ gr.Slider(0,1,step=0.01,value=0.78,label="Execution Velocity"),
235
+ gr.Slider(0,1,step=0.01,value=0.90,label="Founder Commitment Score"),
236
+ gr.Slider(0,1,step=0.01,value=0.70,label="Market Timing Score"),
237
+ gr.Slider(0,1,step=0.01,value=0.65,label="Sector Heat Score"),
238
+ gr.Slider(0,1,step=0.01,value=0.30,label="Competitive Landscape Score"),
239
+ gr.Slider(0,1,step=0.01,value=0.80,label="Regulatory Environment Score"),
240
+ gr.Slider(0,1,step=0.01,value=0.75,label="Product-Market Fit Score"),
241
+ gr.Slider(0,1,step=0.01,value=0.85,label="Transparency Score"),
242
+ gr.Slider(0,1,step=0.01,value=0.82,label="Compliance Score"),
243
+ gr.Slider(0,1,step=0.01,value=0.77,label="Board Independence Score")]
244
+ btn=gr.Button("🔮 ประเมินมูลค่า",variant="primary")
 
 
245
  with gr.Column():
246
+ outputs=[gr.Textbox(label="📊 Correlation",interactive=False),
247
+ gr.Textbox(label="📈 Sharpe Ratio",interactive=False),
248
+ gr.Textbox(label="🎯 BVI Score",interactive=False),
249
+ gr.Textbox(label="⚠️ Risk Level",interactive=False),
250
+ gr.Textbox(label="🌍 World Ranking",interactive=False),
251
+ gr.Textbox(label="💰 Projected ROI (x)",interactive=False),
252
+ gr.File(label="📄 ดาวน์โหลดรายงาน PDF",type="binary")]
253
+ btn.click(evaluate,inputs=inputs,outputs=outputs)
254
+ # ปุ่มสุ่ม
255
+ rng_btn=gr.Button("🎲 สุ่มข้อมูล")
256
+ def random_fill():
257
+ rng=np.random.default_rng(); n=1
258
+ df=pd.DataFrame({"revenue_ttm":rng.lognormal(14,1.5,n),
259
+ "revenue_growth_3y":rng.beta(2,3,n)*5,
260
+ "burn_rate_monthly":rng.exponential(50_000,n),
261
+ "cash_reserves":rng.lognormal(15,1,n),
262
+ "profit_margin":rng.normal(0.1,0.2,n),
263
+ "team_cohesion_score":rng.beta(4,1.5,n),
264
+ "execution_velocity":rng.beta(3,2,n),
265
+ "founder_commitment_score":rng.beta(5,1,n),
266
+ "market_timing_score":rng.beta(3,3,n),
267
+ "sector_heat_score":rng.beta(2,2,n),
268
+ "competitive_landscape_score":rng.beta(2,2,n),
269
+ "regulatory_environment_score":rng.beta(3,1,n),
270
+ "product_market_fit":rng.beta(2,2,n),
271
+ "transparency_score":rng.beta(9,1,n),
272
+ "compliance_score":rng.beta(9,1,n),
273
+ "board_independence":rng.beta(8,2,n)})
274
+ return [v[0] for v in df.iloc[0].tolist()]
275
+ rng_btn.click(random_fill,outputs=inputs)
276
+
277
+ # --------------- 7. Launch ---------------
278
+ demo.queue(max_size=50).launch(server_name="0.0.0.0",server_port=7860,share=True)