Spaces:
Sleeping
Sleeping
Update main.py
Browse files
main.py
CHANGED
|
@@ -1,47 +1,59 @@
|
|
|
|
|
| 1 |
import io
|
| 2 |
import base64
|
|
|
|
| 3 |
from fastapi import FastAPI, UploadFile, File, Form, HTTPException
|
| 4 |
-
from pydantic import BaseModel
|
| 5 |
from diffusers import FluxImg2ImgPipeline
|
| 6 |
from PIL import Image
|
| 7 |
-
import torch
|
| 8 |
|
| 9 |
app = FastAPI()
|
| 10 |
|
| 11 |
-
#
|
| 12 |
-
|
|
|
|
|
|
|
| 13 |
|
| 14 |
-
print("🚀
|
| 15 |
-
# FluxImg2ImgPipeline bisa menangani Text-to-Image maupun Image-to-Image
|
| 16 |
-
pipe = FluxImg2ImgPipeline.from_pretrained(
|
| 17 |
-
model_id,
|
| 18 |
-
torch_dtype=torch.float32 # CPU bekerja paling stabil dengan float32
|
| 19 |
-
)
|
| 20 |
-
pipe.to("cpu")
|
| 21 |
|
| 22 |
-
|
| 23 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
|
|
|
| 25 |
def image_to_base64(image):
|
| 26 |
buffered = io.BytesIO()
|
| 27 |
image.save(buffered, format="JPEG")
|
| 28 |
-
return f"data:image/jpeg;base64,{base64.
|
| 29 |
|
| 30 |
# --- ENDPOINT 1: GENERATE (Text to Image) ---
|
| 31 |
@app.post("/generate")
|
| 32 |
async def generate(prompt: str = Form(...)):
|
|
|
|
|
|
|
|
|
|
| 33 |
try:
|
| 34 |
-
# Untuk generate
|
| 35 |
-
|
|
|
|
| 36 |
prompt=prompt,
|
| 37 |
num_inference_steps=4,
|
| 38 |
guidance_scale=0.0
|
| 39 |
).images[0]
|
| 40 |
|
| 41 |
-
|
| 42 |
-
image.save(buffered, format="JPEG")
|
| 43 |
-
img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
|
| 44 |
-
return {"image": f"data:image/jpeg;base64,{img_str}"}
|
| 45 |
except Exception as e:
|
| 46 |
raise HTTPException(status_code=500, detail=str(e))
|
| 47 |
|
|
@@ -50,28 +62,32 @@ async def generate(prompt: str = Form(...)):
|
|
| 50 |
async def edit(
|
| 51 |
prompt: str = Form(...),
|
| 52 |
image_file: UploadFile = File(...),
|
| 53 |
-
strength: float = Form(0.6)
|
| 54 |
):
|
| 55 |
try:
|
| 56 |
-
#
|
| 57 |
-
|
| 58 |
-
init_image =
|
|
|
|
|
|
|
|
|
|
| 59 |
|
| 60 |
-
# Proses mengubah gambar berdasarkan
|
| 61 |
-
|
| 62 |
prompt=prompt,
|
| 63 |
image=init_image,
|
| 64 |
-
strength=strength,
|
| 65 |
num_inference_steps=4
|
| 66 |
).images[0]
|
| 67 |
|
| 68 |
-
|
| 69 |
-
image.save(buffered, format="JPEG")
|
| 70 |
-
img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
|
| 71 |
-
return {"image": f"data:image/jpeg;base64,{img_str}"}
|
| 72 |
except Exception as e:
|
| 73 |
raise HTTPException(status_code=500, detail=str(e))
|
| 74 |
|
| 75 |
@app.get("/")
|
| 76 |
def health_check():
|
| 77 |
-
return {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
import io
|
| 3 |
import base64
|
| 4 |
+
import torch
|
| 5 |
from fastapi import FastAPI, UploadFile, File, Form, HTTPException
|
|
|
|
| 6 |
from diffusers import FluxImg2ImgPipeline
|
| 7 |
from PIL import Image
|
|
|
|
| 8 |
|
| 9 |
app = FastAPI()
|
| 10 |
|
| 11 |
+
# 1. Konfigurasi Token & Model
|
| 12 |
+
# Pastikan Anda sudah membuat Secret bernama HF_TOKEN di Settings Space Anda
|
| 13 |
+
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 14 |
+
MODEL_ID = "black-forest-labs/FLUX.1-schnell"
|
| 15 |
|
| 16 |
+
print("🚀 Menghubungkan ke Hugging Face...")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
+
try:
|
| 19 |
+
# Menggunakan FluxImg2ImgPipeline karena bisa menangani Generate dan Edit sekaligus
|
| 20 |
+
pipe = FluxImg2ImgPipeline.from_pretrained(
|
| 21 |
+
MODEL_ID,
|
| 22 |
+
torch_dtype=torch.float32, # CPU lebih stabil dengan float32
|
| 23 |
+
token=HF_TOKEN
|
| 24 |
+
)
|
| 25 |
+
# Pindahkan ke CPU
|
| 26 |
+
pipe.to("cpu")
|
| 27 |
+
|
| 28 |
+
# Optimasi RAM agar tidak crash di Hugging Face Free Tier
|
| 29 |
+
pipe.enable_attention_slicing()
|
| 30 |
+
|
| 31 |
+
print("✅ Mamboro AI Engine Berhasil Dimuat di CPU")
|
| 32 |
+
except Exception as e:
|
| 33 |
+
print(f"❌ Gagal memuat model: {e}")
|
| 34 |
|
| 35 |
+
# Fungsi pembantu untuk konversi gambar ke Base64
|
| 36 |
def image_to_base64(image):
|
| 37 |
buffered = io.BytesIO()
|
| 38 |
image.save(buffered, format="JPEG")
|
| 39 |
+
return f"data:image/jpeg;base64,{base64.b64encode(buffered.getvalue()).decode('utf-8')}"
|
| 40 |
|
| 41 |
# --- ENDPOINT 1: GENERATE (Text to Image) ---
|
| 42 |
@app.post("/generate")
|
| 43 |
async def generate(prompt: str = Form(...)):
|
| 44 |
+
if not prompt:
|
| 45 |
+
raise HTTPException(status_code=400, detail="Prompt tidak boleh kosong")
|
| 46 |
+
|
| 47 |
try:
|
| 48 |
+
# Untuk generate di pipeline Img2Img, kita tidak butuh image_file
|
| 49 |
+
# Schnell sangat cepat, hanya butuh 4 steps
|
| 50 |
+
result = pipe(
|
| 51 |
prompt=prompt,
|
| 52 |
num_inference_steps=4,
|
| 53 |
guidance_scale=0.0
|
| 54 |
).images[0]
|
| 55 |
|
| 56 |
+
return {"image": image_to_base64(result)}
|
|
|
|
|
|
|
|
|
|
| 57 |
except Exception as e:
|
| 58 |
raise HTTPException(status_code=500, detail=str(e))
|
| 59 |
|
|
|
|
| 62 |
async def edit(
|
| 63 |
prompt: str = Form(...),
|
| 64 |
image_file: UploadFile = File(...),
|
| 65 |
+
strength: float = Form(0.6) # Nilai 0.1 s/d 0.9
|
| 66 |
):
|
| 67 |
try:
|
| 68 |
+
# Membaca gambar referensi dari HP
|
| 69 |
+
init_content = await image_file.read()
|
| 70 |
+
init_image = Image.open(io.BytesIO(init_content)).convert("RGB")
|
| 71 |
+
|
| 72 |
+
# Perkecil ukuran gambar agar CPU tidak meledak (PENTING!)
|
| 73 |
+
init_image = init_image.resize((512, 512))
|
| 74 |
|
| 75 |
+
# Proses mengubah gambar berdasarkan referensi
|
| 76 |
+
result = pipe(
|
| 77 |
prompt=prompt,
|
| 78 |
image=init_image,
|
| 79 |
+
strength=strength,
|
| 80 |
num_inference_steps=4
|
| 81 |
).images[0]
|
| 82 |
|
| 83 |
+
return {"image": image_to_base64(result)}
|
|
|
|
|
|
|
|
|
|
| 84 |
except Exception as e:
|
| 85 |
raise HTTPException(status_code=500, detail=str(e))
|
| 86 |
|
| 87 |
@app.get("/")
|
| 88 |
def health_check():
|
| 89 |
+
return {
|
| 90 |
+
"status": "Online",
|
| 91 |
+
"engine": "Mamboro AI (Flux Schnell CPU)",
|
| 92 |
+
"device": "CPU"
|
| 93 |
+
}
|