AkashKumarave commited on
Commit
861bd0a
·
verified ·
1 Parent(s): c41faf2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +91 -36
app.py CHANGED
@@ -1,36 +1,91 @@
1
- import gradio as gr
2
- import torch
3
- import modin.pandas as pd
4
- import numpy as np
5
- from diffusers import DiffusionPipeline
6
-
7
- device = "cuda" if torch.cuda.is_available() else "cpu"
8
-
9
- if torch.cuda.is_available():
10
- torch.cuda.max_memory_allocated(device=device)
11
- torch.cuda.empty_cache()
12
- pipe = DiffusionPipeline.from_pretrained("stabilityai/sdxl-turbo", torch_dtype=torch.float16, variant="fp16", use_safetensors=True)
13
- pipe.enable_xformers_memory_efficient_attention()
14
- pipe = pipe.to(device)
15
- torch.cuda.empty_cache()
16
- else:
17
- pipe = DiffusionPipeline.from_pretrained("stabilityai/sdxl-turbo", use_safetensors=True)
18
- pipe = pipe.to(device)
19
-
20
- def genie(prompt, steps, seed):
21
- generator = np.random.seed(0) if seed == 0 else torch.manual_seed(seed)
22
- int_image = pipe(prompt=prompt, generator=generator, num_inference_steps=steps, guidance_scale=0.0).images[0]
23
- return int_image
24
-
25
- gr.Interface(
26
- fn=genie,
27
- inputs=[
28
- gr.Textbox(label="What you want the AI to generate. 77 Token Limit."),
29
- gr.Slider(1, maximum=5, value=2, step=1, label="Number of Iterations"),
30
- gr.Slider(minimum=0, step=1, maximum=999999999999999999, randomize=True),
31
- ],
32
- outputs="image",
33
- title="Stable Diffusion Turbo CPU or GPU",
34
- description="SDXL Turbo CPU or GPU. Currently running on CPU. <br><br><b>WARNING: This model is capable of producing NSFW (Softcore) images.</b>",
35
- article="Created by [Your Name]."
36
- ).launch(debug=True, max_threads=80)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py
2
+ from flask import Flask, request, jsonify
3
+ import razorpay
4
+ import os
5
+ import hmac
6
+ import hashlib
7
+ import json
8
+
9
+ app = Flask(__name__)
10
+
11
+ # Get keys from Hugging Face Secrets (Settings -> Variables)
12
+ RAZORPAY_KEY_ID = os.getenv("RAZORPAY_KEY_ID", "")
13
+ RAZORPAY_KEY_SECRET = os.getenv("RAZORPAY_KEY_SECRET", "")
14
+
15
+ if not RAZORPAY_KEY_ID or not RAZORPAY_KEY_SECRET:
16
+ print("WARNING: Razorpay keys not found in env. Set RAZORPAY_KEY_ID and RAZORPAY_KEY_SECRET in Space secrets.")
17
+
18
+ client = razorpay.Client(auth=(RAZORPAY_KEY_ID, RAZORPAY_KEY_SECRET))
19
+
20
+ def cors_json(resp):
21
+ # Helper to add CORS headers to Flask response dict
22
+ response = jsonify(resp)
23
+ response.headers.add("Access-Control-Allow-Origin", "*")
24
+ response.headers.add("Access-Control-Allow-Headers", "Content-Type")
25
+ return response
26
+
27
+ @app.route("/create-order", methods=["POST", "OPTIONS"])
28
+ def create_order():
29
+ # Preflight
30
+ if request.method == "OPTIONS":
31
+ response = app.response_class(status=204)
32
+ response.headers.add("Access-Control-Allow-Origin", "*")
33
+ response.headers.add("Access-Control-Allow-Headers", "Content-Type")
34
+ return response
35
+
36
+ data = request.get_json(force=True) or {}
37
+ amount = int(data.get("amount", 0)) # amount in rupees from frontend
38
+ if amount <= 0:
39
+ return cors_json({"error": "Invalid amount"}), 400
40
+
41
+ try:
42
+ options = {
43
+ "amount": amount * 100, # paise
44
+ "currency": "INR",
45
+ "receipt": f"receipt_{os.urandom(4).hex()}",
46
+ "payment_capture": 1
47
+ }
48
+ order = client.order.create(options)
49
+ return cors_json(order)
50
+ except Exception as e:
51
+ return cors_json({"error": str(e)}), 500
52
+
53
+ @app.route("/verify-payment", methods=["POST", "OPTIONS"])
54
+ def verify_payment():
55
+ # Verifies signature from Razorpay checkout
56
+ if request.method == "OPTIONS":
57
+ response = app.response_class(status=204)
58
+ response.headers.add("Access-Control-Allow-Origin", "*")
59
+ response.headers.add("Access-Control-Allow-Headers", "Content-Type")
60
+ return response
61
+
62
+ data = request.get_json(force=True) or {}
63
+ try:
64
+ razorpay_order_id = data.get("razorpay_order_id")
65
+ razorpay_payment_id = data.get("razorpay_payment_id")
66
+ razorpay_signature = data.get("razorpay_signature")
67
+
68
+ if not (razorpay_order_id and razorpay_payment_id and razorpay_signature):
69
+ return cors_json({"success": False, "message": "Missing fields"}), 400
70
+
71
+ payload = f"{razorpay_order_id}|{razorpay_payment_id}"
72
+ generated_signature = hmac.new(
73
+ RAZORPAY_KEY_SECRET.encode("utf-8"),
74
+ payload.encode("utf-8"),
75
+ hashlib.sha256
76
+ ).hexdigest()
77
+
78
+ if generated_signature == razorpay_signature:
79
+ return cors_json({"success": True})
80
+ else:
81
+ return cors_json({"success": False, "message": "Invalid signature"}), 400
82
+ except Exception as e:
83
+ return cors_json({"success": False, "message": str(e)}), 500
84
+
85
+ @app.route("/health", methods=["GET"])
86
+ def health():
87
+ return cors_json({"ok": True, "app": "razorpay-backend"})
88
+
89
+ if __name__ == "__main__":
90
+ # Hugging Face Spaces runs on port 7860
91
+ app.run(host="0.0.0.0", port=7860)