Sada8888 commited on
Commit
1837c1f
·
verified ·
1 Parent(s): b6fe3fc

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +80 -0
app.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import uuid
3
+ import requests
4
+ from flask import Flask, request, jsonify, render_template
5
+
6
+ app = Flask(__name__)
7
+
8
+ # خواندن اطلاعات از Secrets های اسپیس
9
+ GITHUB_TOKEN = os.environ.get("GITHUB_TOKEN")
10
+ GITHUB_USER = os.environ.get("GITHUB_USER", "Hamed744")
11
+ GITHUB_REPO = os.environ.get("GITHUB_REPO", "vid-test")
12
+
13
+ # این آدرس به صورت خودکار توسط هاگینگ‌فیس تولید می‌شود
14
+ SPACE_HOST = os.environ.get("SPACE_HOST", "")
15
+ SPACE_URL = f"https://{SPACE_HOST}"
16
+
17
+ @app.route('/')
18
+ def index():
19
+ return render_template('index.html')
20
+
21
+ @app.route('/api/generate', methods=['POST'])
22
+ def generate():
23
+ if not GITHUB_TOKEN:
24
+ return jsonify({"status": "error", "message": "توکن گیت‌هاب در Secrets یافت نشد!"}), 500
25
+
26
+ data = request.json
27
+ prompt = data.get('prompt')
28
+ width = data.get('width', '1024')
29
+ height = data.get('height', '1024')
30
+
31
+ # تولید یک شناسه یکتا برای این درخواست
32
+ run_id = str(uuid.uuid4())
33
+
34
+ # دستور به سرور گیت‌هاب
35
+ url = f"https://api.github.com/repos/{GITHUB_USER}/{GITHUB_REPO}/dispatches"
36
+ headers = {
37
+ "Accept": "application/vnd.github.v3+json",
38
+ "Authorization": f"token {GITHUB_TOKEN}"
39
+ }
40
+
41
+ # ارسال مشخصات و آدرس اسپیس خودمان به گیت‌هاب تا عکس را به همینجا پس بفرستد
42
+ payload = {
43
+ "event_type": "generate-image",
44
+ "client_payload": {
45
+ "prompt": prompt,
46
+ "width": width,
47
+ "height": height,
48
+ "run_id": run_id,
49
+ "space_url": SPACE_URL
50
+ }
51
+ }
52
+
53
+ r = requests.post(url, headers=headers, json=payload)
54
+ if r.status_code == 204:
55
+ return jsonify({"status": "success", "run_id": run_id})
56
+ else:
57
+ return jsonify({"status": "error", "message": r.text}), 400
58
+
59
+ @app.route('/api/webhook/upload', methods=['POST'])
60
+ def webhook_upload():
61
+ # گیت‌هاب وقتی عکس را ساخت، آن را با فرمت POST به این آدرس می‌فرستد
62
+ run_id = request.form.get('run_id')
63
+ if 'file' not in request.files or not run_id:
64
+ return "Invalid request", 400
65
+
66
+ file = request.files['file']
67
+ # ذخیره عکس در حافظه اسپیس داکر شما
68
+ file.save(f"static/images/{run_id}.webp")
69
+ return "OK", 200
70
+
71
+ @app.route('/api/status/<run_id>')
72
+ def check_status(run_id):
73
+ # فرانت‌اند هر ۳ ثانیه چک می‌کند که آیا گیت‌هاب عکس را فرستاده یا نه
74
+ file_path = f"static/images/{run_id}.webp"
75
+ if os.path.exists(file_path):
76
+ return jsonify({"status": "ready", "url": f"/{file_path}"})
77
+ return jsonify({"status": "processing"})
78
+
79
+ if __name__ == '__main__':
80
+ app.run(host='0.0.0.0', port=7860)