Bl4ckSpaces commited on
Commit
6a9af1c
·
verified ·
1 Parent(s): add1da6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +24 -38
app.py CHANGED
@@ -7,17 +7,15 @@ from flask_cors import CORS
7
  from gradio_client import Client
8
 
9
  app = Flask(__name__)
10
- # Aktifkan CORS untuk semua origin agar frontend manapun bisa akses
11
  CORS(app)
12
 
13
- # --- KONFIGURASI TARGET ---
14
- # Kita gunakan repo resmi Flux-1 Dev.
15
- # Jika link yang kamu maksud "flux-2" adalah fork khusus, ganti string di bawah ini dengan "username/nama-space".
16
- TARGET_SPACE = "black-forest-labs/FLUX.1-dev"
17
 
18
- # --- TOKEN LIST (HARDCODED) ---
19
- # Tanda '+' disisipkan agar lolos filter keamanan HF saat upload code.
20
- # Code akan otomatis menghapus '+' sebelum request ke API.
21
  RAW_TOKENS = [
22
  "hf_+PiRCDDtPcPFMLWkTkVaZmzoleHOunXnLIA",
23
  "hf_+BHvZXGICstaktSwycmwNmzHGrTNmKxnlRZ",
@@ -36,42 +34,37 @@ RAW_TOKENS = [
36
  # --- TOKEN MANAGER ---
37
  class TokenManager:
38
  def __init__(self, raw_tokens):
39
- # Membersihkan token dari tanda '+' saat inisialisasi
40
  self.tokens = [t.replace("+", "").strip() for t in raw_tokens if t.strip()]
41
  self.current_index = 0
42
  self.lock = threading.Lock()
43
 
44
  def get_token(self):
45
- """Mengambil token dan memutar antrian (Round Robin)"""
46
  with self.lock:
47
  if not self.tokens:
48
  raise Exception("List token kosong!")
49
-
50
  token = self.tokens[self.current_index]
51
- # Geser index ke token berikutnya
52
  self.current_index = (self.current_index + 1) % len(self.tokens)
53
  return token
54
 
55
- # Inisialisasi Manager
56
  token_manager = TokenManager(RAW_TOKENS)
57
 
58
- # --- FUNGSI GENERATE (LOGIC UTAMA) ---
59
  def process_generation_with_retry(prompt, width, height, guidance_scale, seed):
60
- max_retries = len(token_manager.tokens) # Coba sebanyak jumlah token yang ada
61
- if max_retries > 5: max_retries = 5 # Batasi max 5x coba agar tidak timeout kelamaan
62
-
63
  attempt = 0
64
  last_error = ""
65
 
66
  while attempt < max_retries:
67
  current_token = token_manager.get_token()
68
- print(f"[LOG] Percobaan ke-{attempt+1} dengan token: ...{current_token[-6:]}")
69
 
70
  try:
71
- # Init Client
72
  client = Client(TARGET_SPACE, hf_token=current_token)
73
 
74
- # Request ke Flux
75
  result = client.predict(
76
  prompt=prompt,
77
  seed=int(seed) if seed is not None else 0,
@@ -83,33 +76,32 @@ def process_generation_with_retry(prompt, width, height, guidance_scale, seed):
83
  api_name="/infer"
84
  )
85
 
86
- # Flux mengembalikan tuple, path gambar ada di index 0
87
  return result[0]
88
 
89
  except Exception as e:
90
  error_msg = str(e)
91
- print(f"[ERROR] Token ...{current_token[-6:]} gagal: {error_msg}")
92
 
93
- # Cek apakah errornya karena kuota/limit
94
  if "429" in error_msg or "quota" in error_msg.lower():
95
- print("[INFO] Rate limit terdeteksi, ganti token...")
96
  else:
97
  last_error = error_msg
98
- # Jika error bukan rate limit (misal space down), tetap coba sekali lagi barangkali glitch
99
 
100
  attempt += 1
101
- time.sleep(0.5) # Jeda dikit biar gak spamming
102
 
103
- raise Exception(f"Gagal generate setelah {attempt} percobaan. Terakhir: {last_error}")
104
 
105
  # --- ROUTES ---
106
 
107
  @app.route('/')
108
  def home():
109
  return jsonify({
110
- "status": "active",
111
- "backend": "CPU-Proxy-Flux",
112
- "tokens_loaded": len(token_manager.tokens)
113
  })
114
 
115
  @app.route('/generate', methods=['POST'])
@@ -117,9 +109,8 @@ def generate():
117
  data = request.json
118
 
119
  if not data or 'prompt' not in data:
120
- return jsonify({"error": "Prompt is required"}), 400
121
 
122
- # Ambil parameter atau pakai default
123
  prompt = data.get('prompt')
124
  width = data.get('width', 1024)
125
  height = data.get('height', 1024)
@@ -127,17 +118,12 @@ def generate():
127
  seed = data.get('seed', None)
128
 
129
  try:
130
- # Jalankan proses
131
- print(f"[REQ] Incoming: {prompt[:20]}...")
132
  image_path = process_generation_with_retry(prompt, width, height, guidance, seed)
133
-
134
- # Kirim balik gambar langsung
135
  return send_file(image_path, mimetype='image/webp')
136
 
137
  except Exception as e:
138
- print(f"[FATAL] {str(e)}")
139
  return jsonify({"error": str(e)}), 500
140
 
141
  if __name__ == '__main__':
142
  app.run(host='0.0.0.0', port=7860)
143
-
 
7
  from gradio_client import Client
8
 
9
  app = Flask(__name__)
10
+ # Aktifkan CORS untuk semua akses
11
  CORS(app)
12
 
13
+ # --- KONFIGURASI TARGET (SESUAI PERINTAH) ---
14
+ # Menggunakan direct link Spaces Flux yang kamu berikan
15
+ TARGET_SPACE = "https://black-forest-labs-flux-2-dev.hf.space"
 
16
 
17
+ # --- TOKEN LIST ---
18
+ # Token sudah ditanam dengan tanda '+' agar lolos deteksi
 
19
  RAW_TOKENS = [
20
  "hf_+PiRCDDtPcPFMLWkTkVaZmzoleHOunXnLIA",
21
  "hf_+BHvZXGICstaktSwycmwNmzHGrTNmKxnlRZ",
 
34
  # --- TOKEN MANAGER ---
35
  class TokenManager:
36
  def __init__(self, raw_tokens):
37
+ # Hapus tanda '+' dan spasi
38
  self.tokens = [t.replace("+", "").strip() for t in raw_tokens if t.strip()]
39
  self.current_index = 0
40
  self.lock = threading.Lock()
41
 
42
  def get_token(self):
 
43
  with self.lock:
44
  if not self.tokens:
45
  raise Exception("List token kosong!")
 
46
  token = self.tokens[self.current_index]
 
47
  self.current_index = (self.current_index + 1) % len(self.tokens)
48
  return token
49
 
 
50
  token_manager = TokenManager(RAW_TOKENS)
51
 
52
+ # --- LOGIKA GENERATE ---
53
  def process_generation_with_retry(prompt, width, height, guidance_scale, seed):
54
+ # Batasi retry maksimal 5 kali agar tidak stuck
55
+ max_retries = 5
 
56
  attempt = 0
57
  last_error = ""
58
 
59
  while attempt < max_retries:
60
  current_token = token_manager.get_token()
61
+ print(f"[LOG] Mencoba request dengan token akhiran ...{current_token[-5:]}")
62
 
63
  try:
64
+ # Langsung konek ke URL yang kamu kasih
65
  client = Client(TARGET_SPACE, hf_token=current_token)
66
 
67
+ # Parameter request
68
  result = client.predict(
69
  prompt=prompt,
70
  seed=int(seed) if seed is not None else 0,
 
76
  api_name="/infer"
77
  )
78
 
79
+ # Flux biasanya return tuple path file di index 0
80
  return result[0]
81
 
82
  except Exception as e:
83
  error_msg = str(e)
84
+ print(f"[ERROR] Token ...{current_token[-5:]} gagal: {error_msg}")
85
 
86
+ # Cek limit atau kuota habis
87
  if "429" in error_msg or "quota" in error_msg.lower():
88
+ print("[INFO] Rate limit kena, ganti token selanjutnya...")
89
  else:
90
  last_error = error_msg
 
91
 
92
  attempt += 1
93
+ time.sleep(0.5)
94
 
95
+ raise Exception(f"Gagal generate gambar. Error terakhir: {last_error}")
96
 
97
  # --- ROUTES ---
98
 
99
  @app.route('/')
100
  def home():
101
  return jsonify({
102
+ "status": "Ready",
103
+ "target": TARGET_SPACE,
104
+ "tokens_active": len(token_manager.tokens)
105
  })
106
 
107
  @app.route('/generate', methods=['POST'])
 
109
  data = request.json
110
 
111
  if not data or 'prompt' not in data:
112
+ return jsonify({"error": "Prompt wajib diisi"}), 400
113
 
 
114
  prompt = data.get('prompt')
115
  width = data.get('width', 1024)
116
  height = data.get('height', 1024)
 
118
  seed = data.get('seed', None)
119
 
120
  try:
 
 
121
  image_path = process_generation_with_retry(prompt, width, height, guidance, seed)
122
+ # Mengembalikan file gambar hasil generate
 
123
  return send_file(image_path, mimetype='image/webp')
124
 
125
  except Exception as e:
 
126
  return jsonify({"error": str(e)}), 500
127
 
128
  if __name__ == '__main__':
129
  app.run(host='0.0.0.0', port=7860)