Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
import logging
|
| 2 |
-
from fastapi import FastAPI, UploadFile, File, HTTPException, Form
|
| 3 |
from fastapi.middleware.cors import CORSMiddleware
|
| 4 |
-
from fastapi.responses import FileResponse
|
| 5 |
import requests
|
| 6 |
import base64
|
| 7 |
import os
|
|
@@ -10,18 +10,20 @@ import jwt
|
|
| 10 |
from pathlib import Path
|
| 11 |
from typing import List
|
| 12 |
import io
|
|
|
|
|
|
|
| 13 |
|
| 14 |
# Configure logging
|
| 15 |
logging.basicConfig(level=logging.INFO)
|
| 16 |
logger = logging.getLogger(__name__)
|
| 17 |
|
| 18 |
# Initialize FastAPI app
|
| 19 |
-
app = FastAPI(title="Kling AI Multi-Image Generator API")
|
| 20 |
|
| 21 |
# Enable CORS for the frontend
|
| 22 |
app.add_middleware(
|
| 23 |
CORSMiddleware,
|
| 24 |
-
allow_origins=["https://hivili.web.app"], #
|
| 25 |
allow_credentials=True,
|
| 26 |
allow_methods=["*"],
|
| 27 |
allow_headers=["*"],
|
|
@@ -33,6 +35,11 @@ ACCESS_KEY_SECRET = os.getenv("ACCESS_KEY_SECRET", "TTepeLyBterLNM3brYPGmdndBnny
|
|
| 33 |
API_BASE_URL = "https://api-singapore.klingai.com"
|
| 34 |
CREATE_TASK_ENDPOINT = f"{API_BASE_URL}/v1/images/multi-image2image"
|
| 35 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
# ===== AUTHENTICATION =====
|
| 37 |
def generate_jwt_token():
|
| 38 |
"""Generate JWT token for API authentication"""
|
|
@@ -110,6 +117,38 @@ def check_task_status(task_id: str):
|
|
| 110 |
except requests.exceptions.RequestException as e:
|
| 111 |
raise HTTPException(status_code=500, detail=f"Status check failed: {str(e)}")
|
| 112 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
# ===== MAIN PROCESSING =====
|
| 114 |
async def generate_image(subject_images: List[bytes], prompt: str):
|
| 115 |
"""Handle complete image generation workflow"""
|
|
@@ -175,9 +214,46 @@ async def generate_image_endpoint(
|
|
| 175 |
logger.error(f"Error in /generate: {str(e)}")
|
| 176 |
raise HTTPException(status_code=500, detail=str(e))
|
| 177 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 178 |
@app.get("/")
|
| 179 |
async def index():
|
| 180 |
-
return {"status": "Kling AI Multi-Image Generator API is running"}
|
| 181 |
|
| 182 |
if __name__ == "__main__":
|
| 183 |
import uvicorn
|
|
|
|
| 1 |
import logging
|
| 2 |
+
from fastapi import FastAPI, UploadFile, File, HTTPException, Form, Request
|
| 3 |
from fastapi.middleware.cors import CORSMiddleware
|
| 4 |
+
from fastapi.responses import FileResponse, JSONResponse
|
| 5 |
import requests
|
| 6 |
import base64
|
| 7 |
import os
|
|
|
|
| 10 |
from pathlib import Path
|
| 11 |
from typing import List
|
| 12 |
import io
|
| 13 |
+
import razorpay
|
| 14 |
+
from razorpay.errors import SignatureVerificationError
|
| 15 |
|
| 16 |
# Configure logging
|
| 17 |
logging.basicConfig(level=logging.INFO)
|
| 18 |
logger = logging.getLogger(__name__)
|
| 19 |
|
| 20 |
# Initialize FastAPI app
|
| 21 |
+
app = FastAPI(title="Kling AI Multi-Image Generator API with Razorpay")
|
| 22 |
|
| 23 |
# Enable CORS for the frontend
|
| 24 |
app.add_middleware(
|
| 25 |
CORSMiddleware,
|
| 26 |
+
allow_origins=["https://hivili.web.app"], # Update with your frontend URL
|
| 27 |
allow_credentials=True,
|
| 28 |
allow_methods=["*"],
|
| 29 |
allow_headers=["*"],
|
|
|
|
| 35 |
API_BASE_URL = "https://api-singapore.klingai.com"
|
| 36 |
CREATE_TASK_ENDPOINT = f"{API_BASE_URL}/v1/images/multi-image2image"
|
| 37 |
|
| 38 |
+
# ===== RAZORPAY CONFIGURATION =====
|
| 39 |
+
RAZORPAY_KEY_ID = os.getenv("RAZORPAY_KEY_ID") # Set in environment variables
|
| 40 |
+
RAZORPAY_KEY_SECRET = os.getenv("RAZORPAY_KEY_SECRET") # Set in environment variables
|
| 41 |
+
razorpay_client = razorpay.Client(auth=(RAZORPAY_KEY_ID, RAZORPAY_KEY_SECRET))
|
| 42 |
+
|
| 43 |
# ===== AUTHENTICATION =====
|
| 44 |
def generate_jwt_token():
|
| 45 |
"""Generate JWT token for API authentication"""
|
|
|
|
| 117 |
except requests.exceptions.RequestException as e:
|
| 118 |
raise HTTPException(status_code=500, detail=f"Status check failed: {str(e)}")
|
| 119 |
|
| 120 |
+
# ===== RAZORPAY FUNCTIONS =====
|
| 121 |
+
def create_razorpay_order(amount: int, currency: str = "INR"):
|
| 122 |
+
"""Create a Razorpay order"""
|
| 123 |
+
try:
|
| 124 |
+
order_data = {
|
| 125 |
+
"amount": amount * 100, # Amount in paise (e.g., 500 INR = 50000 paise)
|
| 126 |
+
"currency": currency,
|
| 127 |
+
"payment_capture": 1 # Auto-capture payment
|
| 128 |
+
}
|
| 129 |
+
order = razorpay_client.order.create(data=order_data)
|
| 130 |
+
return order
|
| 131 |
+
except Exception as e:
|
| 132 |
+
logger.error(f"Failed to create Razorpay order: {str(e)}")
|
| 133 |
+
raise HTTPException(status_code=500, detail=f"Failed to create order: {str(e)}")
|
| 134 |
+
|
| 135 |
+
def verify_payment_signature(order_id: str, payment_id: str, signature: str):
|
| 136 |
+
"""Verify Razorpay payment signature"""
|
| 137 |
+
try:
|
| 138 |
+
params_dict = {
|
| 139 |
+
"razorpay_order_id": order_id,
|
| 140 |
+
"razorpay_payment_id": payment_id,
|
| 141 |
+
"razorpay_signature": signature
|
| 142 |
+
}
|
| 143 |
+
razorpay_client.utility.verify_payment_signature(params_dict)
|
| 144 |
+
return True
|
| 145 |
+
except SignatureVerificationError as e:
|
| 146 |
+
logger.error(f"Payment signature verification failed: {str(e)}")
|
| 147 |
+
return False
|
| 148 |
+
except Exception as e:
|
| 149 |
+
logger.error(f"Error verifying payment signature: {str(e)}")
|
| 150 |
+
raise HTTPException(status_code=500, detail=f"Verification error: {str(e)}")
|
| 151 |
+
|
| 152 |
# ===== MAIN PROCESSING =====
|
| 153 |
async def generate_image(subject_images: List[bytes], prompt: str):
|
| 154 |
"""Handle complete image generation workflow"""
|
|
|
|
| 214 |
logger.error(f"Error in /generate: {str(e)}")
|
| 215 |
raise HTTPException(status_code=500, detail=str(e))
|
| 216 |
|
| 217 |
+
@app.post("/create-order")
|
| 218 |
+
async def create_order(amount: int = Form(...)):
|
| 219 |
+
"""Create a Razorpay order for payment"""
|
| 220 |
+
if not RAZORPAY_KEY_ID or not RAZORPAY_KEY_SECRET:
|
| 221 |
+
raise HTTPException(status_code=500, detail="Razorpay configuration missing")
|
| 222 |
+
|
| 223 |
+
try:
|
| 224 |
+
order = create_razorpay_order(amount)
|
| 225 |
+
return JSONResponse(content={
|
| 226 |
+
"order_id": order["id"],
|
| 227 |
+
"amount": order["amount"],
|
| 228 |
+
"currency": order["currency"],
|
| 229 |
+
"key_id": RAZORPAY_KEY_ID
|
| 230 |
+
})
|
| 231 |
+
except Exception as e:
|
| 232 |
+
logger.error(f"Error creating order: {str(e)}")
|
| 233 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 234 |
+
|
| 235 |
+
@app.post("/verify-payment")
|
| 236 |
+
async def verify_payment(
|
| 237 |
+
razorpay_order_id: str = Form(...),
|
| 238 |
+
razorpay_payment_id: str = Form(...),
|
| 239 |
+
razorpay_signature: str = Form(...)
|
| 240 |
+
):
|
| 241 |
+
"""Verify Razorpay payment signature"""
|
| 242 |
+
try:
|
| 243 |
+
is_valid = verify_payment_signature(razorpay_order_id, razorpay_payment_id, razorpay_signature)
|
| 244 |
+
if is_valid:
|
| 245 |
+
# Here you can update user subscription status in your database
|
| 246 |
+
# For example, update a user's plan to "premium" or increment credits
|
| 247 |
+
return JSONResponse(content={"status": "success", "message": "Payment verified successfully"})
|
| 248 |
+
else:
|
| 249 |
+
raise HTTPException(status_code=400, detail="Payment verification failed")
|
| 250 |
+
except Exception as e:
|
| 251 |
+
logger.error(f"Error verifying payment: {str(e)}")
|
| 252 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 253 |
+
|
| 254 |
@app.get("/")
|
| 255 |
async def index():
|
| 256 |
+
return {"status": "Kling AI Multi-Image Generator API with Razorpay is running"}
|
| 257 |
|
| 258 |
if __name__ == "__main__":
|
| 259 |
import uvicorn
|