BehradB2 commited on
Commit
5fe8ee1
·
verified ·
1 Parent(s): 8ac314b

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +21 -128
main.py CHANGED
@@ -1,144 +1,37 @@
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
- }
 
1
  import os
2
  import itertools
 
3
  import google.generativeai as genai
4
  from fastapi import FastAPI, HTTPException, Header
 
 
5
  from pydantic import BaseModel
6
 
7
+ # پیدا کردن کلیدها
 
 
 
8
  all_keys = [os.environ.get(k) for k in os.environ.keys() if k.startswith("KEY_")]
 
 
 
 
 
 
9
  key_cycle = itertools.cycle(all_keys)
10
 
11
+ app = FastAPI()
 
 
 
 
 
 
 
 
 
 
12
 
13
  class AIRequest(BaseModel):
14
  prompt: str
15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  @app.post("/ask")
17
  async def ask_ai(request: AIRequest, x_api_token: str = Header(...)):
 
18
  if x_api_token != "Behrad_King_2026":
19
+ raise HTTPException(status_code=403, detail="رمز اشتباه")
20
+
21
+ if not all_keys:
22
+ return {"status": "error", "message": "هیچ سکرتی با نام KEY_ پیدا نشد!"}
23
+
24
+ current_key = next(key_cycle)
25
+ try:
26
+ genai.configure(api_key=current_key)
27
+ model = genai.GenerativeModel('gemini-1.5-flash')
28
+ response = model.generate_content(request.prompt)
29
+ return {"status": "success", "answer": response.text}
30
+
31
+ except Exception as e:
32
+ # اینجا مهم است: نمایش ارور واقعی گوگل
33
+ return {
34
+ "status": "error",
35
+ "key_prefix": current_key[:8] if current_key else "None",
36
+ "google_says": str(e) # این به ما می‌گوید مشکل چیست
37
+ }