BehradB2 commited on
Commit
8ac314b
·
verified ·
1 Parent(s): 7f8799e

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +97 -33
main.py CHANGED
@@ -1,80 +1,144 @@
1
- from fastapi import FastAPI, HTTPException, Header, Depends
 
 
 
 
2
  from fastapi.responses import HTMLResponse
3
  from fastapi.middleware.cors import CORSMiddleware
4
  from pydantic import BaseModel
5
- import google.generativeai as genai
6
- import itertools
7
- import datetime
8
 
9
  # ==========================================
10
- # ۱. تنظیمات و لیست کلیدها
11
  # ==========================================
12
- # بهراد جان، حتماً تمام کلیدهای این لیست را با کلیدهای واقعی جایگزین کن
13
- API_KEYS = [
14
- "AIzaSyBBRlkT-86gGwY9UvrYMSBmIetZK5Uu9xI",
15
- "AIzaSyD-7i8Y2iAiqNXJY1jklcGZNk6GdUsymOE",
16
- "AIzaSyB2_RkZdEaVqiq7Qu3oMB1ya86cJHe0lLM"
17
- ]
18
 
19
- key_cycle = itertools.cycle(API_KEYS)
20
- MY_SECRET_PASS = "Behrad_King_2026"
 
 
21
 
 
 
 
22
  stats = {
23
  "total": 0, "ok": 0, "err": 0,
24
  "start": datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
25
  }
26
 
27
- app = FastAPI()
28
- app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])
 
 
 
29
 
30
  class AIRequest(BaseModel):
31
  prompt: str
32
 
33
  # ==========================================
34
- # ۲. ظاهر سایت (بدون تغییر)
35
  # ==========================================
36
  @app.get("/", response_class=HTMLResponse)
37
  async def public_ui():
38
- return '<body style="background:#f5f5f7;font-family:sans-serif;display:flex;align-items:center;justify-content:center;height:100vh;">' \
39
- '<div style="background:white;padding:50px;border-radius:30px;box-shadow:0 10px 30px rgba(0,0,0,0.05);text-align:center;">' \
40
- '<h1>Behrad AI Core</h1><p style="color:#888;">سیستم آماده پردازش است.</p></div></body>'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
 
 
 
 
42
  @app.get("/admin", response_class=HTMLResponse)
43
  async def admin_ui():
44
- return f'<body style="background:#000;color:#0f0;font-family:monospace;padding:30px;">' \
45
- f'<h2>[ ADMIN PANEL ]</h2><p>REQS: {stats["total"]} | OK: {stats["ok"]} | ERR: {stats["err"]}</p>' \
46
- f'<p>Keys: {len(API_KEYS)}</p></body>'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
 
48
  # ==========================================
49
- # ۳. هسته هوشمند (با قابلیت پرش از کلید خراب)
50
  # ==========================================
51
  @app.post("/ask")
52
  async def ask_ai(request: AIRequest, x_api_token: str = Header(...)):
53
- if x_api_token != MY_SECRET_PASS:
 
54
  stats["err"] += 1
55
- raise HTTPException(status_code=403, detail="Access Denied")
56
 
57
  stats["total"] += 1
58
 
59
- # تلاش برای گرفتن جواب با چرخیدن بین کلیدها (تا ۳ بار تلاش)
60
- for _ in range(len(API_KEYS)):
61
  current_key = next(key_cycle)
62
  try:
 
63
  genai.configure(api_key=current_key)
64
- # استفاده از مدل Pro به عنوان پایدارترین مدل
65
- model = genai.GenerativeModel('gemini-pro')
 
66
  response = model.generate_content(request.prompt)
67
 
68
  stats["ok"] += 1
69
- return {"status": "success", "answer": response.text, "key_used": current_key[:8]}
 
 
 
 
70
 
71
  except Exception as e:
72
- print(f"Key failed: {current_key[:8]} - Error: {str(e)}")
73
- continue # اگر این کلید خطا داد، برو سراغ کلید بعدی
74
 
75
  stats["err"] += 1
76
  return {
77
  "status": "error",
78
- "message": "تمام کلیدهای شما با خطا مواجه شدند. لطفاً کلیدها را در Google AI Studio چک کنید.",
79
  "debug": "All keys exhausted"
80
  }
 
1
+ import os
2
+ import itertools
3
+ import datetime
4
+ import google.generativeai as genai
5
+ from fastapi import FastAPI, HTTPException, Header
6
  from fastapi.responses import HTMLResponse
7
  from fastapi.middleware.cors import CORSMiddleware
8
  from pydantic import BaseModel
 
 
 
9
 
10
  # ==========================================
11
+ # ۱. سیستم شناسایی هوشمند کلیدها از Secrets
12
  # ==========================================
13
+ # این بخش تمام سکرت‌هایی که با KEY_ شروع می‌شوند را پیدا می‌کند
14
+ all_keys = [os.environ.get(k) for k in os.environ.keys() if k.startswith("KEY_")]
 
 
 
 
15
 
16
+ # اگر هیچ سکرتی ست نکرده باشی، یک پیام راهنما چاپ می‌کند
17
+ if not all_keys:
18
+ print("⚠️ هشدار: هیچ کلیدی با پیشوند KEY_ در سکرت‌ها پیدا نشد!")
19
+ all_keys = ["NO_KEY_FOUND"]
20
 
21
+ key_cycle = itertools.cycle(all_keys)
22
+
23
+ # آمارهای زنده پنل مدیریت
24
  stats = {
25
  "total": 0, "ok": 0, "err": 0,
26
  "start": datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
27
  }
28
 
29
+ app = FastAPI(title="Behrad AI Core V3.5")
30
+
31
+ app.add_middleware(
32
+ CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"]
33
+ )
34
 
35
  class AIRequest(BaseModel):
36
  prompt: str
37
 
38
  # ==========================================
39
+ # ۲. ظاهر لوکس اپل (آدرس /)
40
  # ==========================================
41
  @app.get("/", response_class=HTMLResponse)
42
  async def public_ui():
43
+ return """
44
+ <!DOCTYPE html>
45
+ <html lang="fa" dir="rtl">
46
+ <head>
47
+ <meta charset="UTF-8">
48
+ <style>
49
+ body { background: #f5f5f7; font-family: -apple-system, sans-serif; display: flex; align-items: center; justify-content: center; height: 100vh; margin: 0; }
50
+ .glass-card { background: rgba(255, 255, 255, 0.7); backdrop-filter: blur(25px); border-radius: 40px; padding: 60px; box-shadow: 0 30px 60px rgba(0,0,0,0.06); text-align: center; border: 1px solid rgba(255,255,255,0.4); max-width: 480px; }
51
+ h1 { font-size: 52px; font-weight: 700; color: #1d1d1f; letter-spacing: -2px; margin-bottom: 15px; }
52
+ p { color: #86868b; font-size: 20px; font-weight: 400; line-height: 1.6; }
53
+ .btn { display: inline-block; margin-top: 40px; padding: 12px 30px; background: #0071e3; color: white; border-radius: 25px; text-decoration: none; font-size: 15px; font-weight: 500; }
54
+ </style>
55
+ </head>
56
+ <body>
57
+ <div class="glass-card">
58
+ <h1>Behrad AI</h1>
59
+ <p>سادگی در خدمت قدرت. هوش مصنوعی اختصاصی بهراد برای پروژه‌های هوشمند آینده.</p>
60
+ <a href="/admin" class="btn">پنل مهندسی</a>
61
+ </div>
62
+ </body>
63
+ </html>
64
+ """
65
 
66
+ # ==========================================
67
+ # ۳. پنل مدیریت مهندسی (آدرس /admin)
68
+ # ==========================================
69
  @app.get("/admin", response_class=HTMLResponse)
70
  async def admin_ui():
71
+ return f"""
72
+ <!DOCTYPE html>
73
+ <html>
74
+ <head>
75
+ <title>Engineering Panel</title>
76
+ <style>
77
+ body {{ background: #080808; color: #4af626; font-family: 'Courier New', monospace; padding: 40px; }}
78
+ .panel {{ border: 1px solid #4af626; padding: 30px; border-radius: 8px; box-shadow: 0 0 25px rgba(74, 246, 38, 0.15); }}
79
+ .stats {{ display: grid; grid-template-columns: repeat(4, 1fr); gap: 20px; margin-top: 30px; }}
80
+ .box {{ border: 1px dashed #4af626; padding: 20px; text-align: center; }}
81
+ .box div {{ font-size: 32px; font-weight: bold; margin-top: 10px; }}
82
+ .badge {{ color: black; background: #4af626; padding: 2px 10px; border-radius: 4px; font-weight: bold; }}
83
+ </style>
84
+ </head>
85
+ <body>
86
+ <div class="panel">
87
+ <h2>[ BEHRAD_SYSTEM_MONITOR ] <span class="badge">V3.5</span></h2>
88
+ <p>ACTIVE MODEL: gemini-1.5-flash | STATUS: OPERATIONAL</p>
89
+ <div class="stats">
90
+ <div class="box">REQUESTS<div>{stats['total']}</div></div>
91
+ <div class="box">SUCCESS<div>{stats['ok']}</div></div>
92
+ <div class="box">ERRORS<div>{stats['err']}</div></div>
93
+ <div class="box">KEY_SECRETS<div>{len(all_keys)}</div></div>
94
+ </div>
95
+ <div style="margin-top: 20px; font-size: 13px; opacity: 0.7;">
96
+ > Key Rotation: ENABLED<br>
97
+ > Security Token: Behrad_King_2026<br>
98
+ > Cloud Server: Hugging Face US
99
+ </div>
100
+ </div>
101
+ </body>
102
+ </html>
103
+ """
104
 
105
  # ==========================================
106
+ # ۴. هسته پردازشی (Anti-Limit Logic)
107
  # ==========================================
108
  @app.post("/ask")
109
  async def ask_ai(request: AIRequest, x_api_token: str = Header(...)):
110
+ # تایید هویت
111
+ if x_api_token != "Behrad_King_2026":
112
  stats["err"] += 1
113
+ raise HTTPException(status_code=403, detail="⛔ Access Denied: رمز عبور اشتباه است!")
114
 
115
  stats["total"] += 1
116
 
117
+ # تلاش برای استفاده از کلیدها تا زمانی که یکی جواب بدهد
118
+ for _ in range(len(all_keys)):
119
  current_key = next(key_cycle)
120
  try:
121
+ # تنظیم جمنای
122
  genai.configure(api_key=current_key)
123
+ # استفاده از نام استاندارد مدل برای جلوگیری از 404
124
+ model = genai.GenerativeModel('gemini-1.5-flash')
125
+
126
  response = model.generate_content(request.prompt)
127
 
128
  stats["ok"] += 1
129
+ return {
130
+ "status": "success",
131
+ "answer": response.text,
132
+ "credits": "Powered by Behrad AI Core"
133
+ }
134
 
135
  except Exception as e:
136
+ print(f"Key failed: {current_key[:8]}... Error: {str(e)}")
137
+ continue # رفتن به کلید بعدی در صورت خطا
138
 
139
  stats["err"] += 1
140
  return {
141
  "status": "error",
142
+ "message": "تمامی کلیدهای شما با خطا مواجه شدند. لطفاً سکرت‌ها را در تنظیمات چک کنید.",
143
  "debug": "All keys exhausted"
144
  }