Semih25 commited on
Commit
e2e7ecb
·
verified ·
1 Parent(s): 752c4e1

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +151 -0
app.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py — İki takım adıyla tek maç analizi (API-Sports)
2
+ import os, requests, math, numpy as np, pandas as pd, streamlit as st
3
+
4
+ st.set_page_config(page_title="⚽ İki Takım Analizi", layout="centered")
5
+ API_BASE = "https://v3.football.api-sports.io"
6
+
7
+ # ---- API KEY ----
8
+ prefill = os.environ.get("API_FOOTBALL_KEY", "")
9
+ try:
10
+ prefill = prefill or st.secrets.get("API_FOOTBALL_KEY", "")
11
+ except Exception:
12
+ pass
13
+ API_KEY = st.text_input("API-Sports anahtarın", value=prefill, type="password")
14
+ HEADERS = {"x-apisports-key": API_KEY} if API_KEY else {}
15
+
16
+ # ---------- Yardımcılar ----------
17
+ def get(url, params=None):
18
+ return requests.get(f"{API_BASE}{url}", headers=HEADERS, params=params or {}, timeout=40)
19
+
20
+ def search_team(name: str):
21
+ """En iyi eşleşen takımı döndür (id, ad, ülke)."""
22
+ r = get("/teams", {"search": name})
23
+ if r.status_code != 200: return None
24
+ resp = r.json().get("response", [])
25
+ if not resp: return None
26
+ t = resp[0]
27
+ return {"id": t["team"]["id"], "name": t["team"]["name"], "country": t["team"]["country"]}
28
+
29
+ def lastN_profile(team_id: int, n: int = 20):
30
+ """FREE planda çalışır: lig/sezon filtresi olmadan son N maçtan ortalama üretir."""
31
+ r = get("/fixtures", {"team": team_id, "last": n})
32
+ if r.status_code != 200: return None
33
+ fx = r.json().get("response", [])
34
+ if not fx: return None
35
+
36
+ def agg(as_home=None):
37
+ gs=ga=cnt=0
38
+ for f in fx:
39
+ th, ta = f["teams"]["home"]["id"], f["teams"]["away"]["id"]
40
+ gh, ga_ = (f["goals"]["home"] or 0), (f["goals"]["away"] or 0)
41
+ if as_home is True and th != team_id: continue
42
+ if as_home is False and ta != team_id: continue
43
+ if th == team_id: gs += gh; ga += ga_
44
+ else: gs += ga_; ga += gh
45
+ cnt += 1
46
+ if cnt==0: return 0.0, 0.0
47
+ return gs/cnt, ga/cnt
48
+
49
+ hs,hc = agg(True) # ev oynarken
50
+ as_,ac = agg(False) # deplasmanda
51
+ overall = (hs+as_)/2 if (hs and as_) else max(hs,as_,0.0)
52
+
53
+ return {"home_scored":hs, "home_conceded":hc, "away_scored":as_, "away_conceded":ac, "overall":overall}
54
+
55
+ def next_h2h(home_id: int, away_id: int):
56
+ """İki takımın sıradaki resmî maçını bul (varsa)."""
57
+ r = get("/fixtures/headtohead", {"h2h": f"{home_id}-{away_id}", "next": 1})
58
+ if r.status_code != 200: return None
59
+ resp = r.json().get("response", [])
60
+ return resp[0] if resp else None
61
+
62
+ def poisson_pmf(k, lam):
63
+ return math.exp(-lam) * (lam**k) / math.factorial(k) if lam>0 else (1.0 if k==0 else 0.0)
64
+
65
+ def score_matrix(lh, la, max_g=6):
66
+ h = np.array([poisson_pmf(i, lh) for i in range(max_g+1)])
67
+ a = np.array([poisson_pmf(j, la) for j in range(max_g+1)])
68
+ M = np.outer(h, a); M /= M.sum(); return M
69
+
70
+ def probs_1x2(M):
71
+ p1 = np.tril(M,-1).sum(); px = np.trace(M); p2 = np.triu(M,1).sum()
72
+ return float(p1), float(px), float(p2)
73
+
74
+ def ou_prob(M, line=2.5):
75
+ n=M.shape[0]; return float(sum(M[i,j] for i in range(n) for j in range(n) if i+j>line))
76
+
77
+ def btts_prob(M):
78
+ n=M.shape[0]; return float(sum(M[i,j] for i in range(n) for j in range(n) if i>=1 and j>=1))
79
+
80
+ def estimate_lambdas(home_prof, away_prof):
81
+ """Ev λ ve Dep λ: ev hücum + rakibin deplasman savunması harmanı (free-friendly)."""
82
+ if not home_prof or not away_prof:
83
+ return 1.5, 1.2, "fallback"
84
+
85
+ lam_h = 0.6*max(home_prof["home_scored"],0.01) + 0.4*max(away_prof["away_conceded"],0.01)
86
+ lam_a = 0.6*max(away_prof["away_scored"],0.01) + 0.4*max(home_prof["home_conceded"],0.01)
87
+ # genel ofans ile yumuşat
88
+ lam_h = 0.7*lam_h + 0.3*home_prof["overall"]
89
+ lam_a = 0.7*lam_a + 0.3*away_prof["overall"]
90
+ lam_h = float(np.clip(lam_h, 0.2, 3.8))
91
+ lam_a = float(np.clip(lam_a, 0.2, 3.8))
92
+ return lam_h, lam_a, "lastN"
93
+
94
+ # ---------- UI ----------
95
+ st.title("⚽ İki Takım — Maç Olasılık Analizi")
96
+
97
+ c1, c2 = st.columns(2)
98
+ with c1: team_home_name = st.text_input("Ev sahibi (ör. Fenerbahçe)", "")
99
+ with c2: team_away_name = st.text_input("Deplasman (ör. Galatasaray)", "")
100
+
101
+ if st.button("🔎 Analiz Et"):
102
+ if not API_KEY:
103
+ st.error("Önce API anahtarını yazmalısın."); st.stop()
104
+
105
+ # 1) Takımları bul
106
+ th = search_team(team_home_name.strip())
107
+ ta = search_team(team_away_name.strip())
108
+ if not th or not ta:
109
+ st.error("Takım(lar) bulunamadı. İsimleri biraz daha net yazmayı dene.")
110
+ st.stop()
111
+
112
+ st.write(f"**Eşleşen takımlar:** {th['name']} ({th['country']}) vs {ta['name']} ({ta['country']})")
113
+
114
+ # 2) Sıradaki resmi maç (varsa)
115
+ fx = next_h2h(th["id"], ta["id"])
116
+ if fx:
117
+ dt_str = fx["fixture"]["date"].replace("T"," ")[:16]
118
+ st.caption(f"Bulunan resmi maç: **{dt_str}** – Lig: {fx['league']['country']} / {fx['league']['name']}")
119
+
120
+ # 3) Profiller (son 20 – free uyumlu)
121
+ ph = lastN_profile(th["id"], 20)
122
+ pa = lastN_profile(ta["id"], 20)
123
+
124
+ lam_h, lam_a, src = estimate_lambdas(ph, pa)
125
+ M = score_matrix(lam_h, lam_a)
126
+ p1, px, p2 = probs_1x2(M)
127
+ p_ou25 = ou_prob(M, 2.5)
128
+ p_btts = btts_prob(M)
129
+
130
+ # 4) Özet çıktı
131
+ st.subheader("📈 Olasılıklar")
132
+ res = pd.DataFrame({
133
+ "Metrix": ["Ev kazanır", "Beraberlik", "Dep kazanır", "Üst 2.5", "KG Var"],
134
+ "Olasılık %": [round(p1*100,1), round(px*100,1), round(p2*100,1),
135
+ round(p_ou25*100,1), round(p_btts*100,1)]
136
+ })
137
+ st.table(res)
138
+
139
+ st.caption(f"λ Ev = {lam_h:.2f}, λ Dep = {lam_a:.2f} • Kaynak: {src} (son 20 maç)")
140
+
141
+ # 5) Skor olasılıkları (en olası 5 skor)
142
+ scores = []
143
+ for i in range(0,6):
144
+ for j in range(0,6):
145
+ prob = M[i,j]
146
+ scores.append((f"{i}-{j}", prob))
147
+ top = sorted(scores, key=lambda x: x[1], reverse=True)[:5]
148
+ df_top = pd.DataFrame({"Skor": [t[0] for t in top],
149
+ "Olasılık %": [round(t[1]*100,2) for t in top]})
150
+ st.subheader("🔝 En olası skorlar")
151
+ st.table(df_top)