Update api.py
Browse files1234567891011121314151617183 unmodified lines2223242526272 unmodified lines30313233343536373839404142434445464748495051525354555657585960616263646566676869707172736 unmodified lines80818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541558 unmodified lines1641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022031 unmodified line2052062072082092102 unmodified lines2132142152162172182192202212 unmodified lines2242252262272282292302312322332342351 unmodified line2372382392402412422432442451 unmodified line2472482492502512522 unmodified lines255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301import osimport globimport torchfrom flask import Flask, request, jsonify, send_file, render_template_stringfrom diffusers import StableDiffusionPipeline, AutoencoderKLfrom PIL import Image, ImageFilterfrom deep_translator import GoogleTranslatorprint("IMAGE PRO AI STARTING...")# ===============================# PATHS# ===============================CACHE_DIR = "F:/AI_models"OUTPUT_DIR = "outputs"os.makedirs(OUTPUT_DIR, exist_ok=True)3 unmodified lines# ===============================def translate_prompt(prompt):try:prompt_en = GoogleTranslator(source="pl", target="en").translate(prompt)print("PL:", prompt)2 unmodified linesexcept:return prompt# ===============================# FIND VAE# ===============================print("Searching VAE...")vae = Nonevae_files = glob.glob(r"F:\AI_models\models--stabilityai--sd-vae-ft-mse\snapshots\*\vae-ft-mse-840000-ema-pruned.safetensors")if len(vae_files) > 0:VAE_PATH = vae_files[0]print("VAE FOUND:", VAE_PATH)try:vae = AutoencoderKL.from_single_file(VAE_PATH,torch_dtype=torch.float32)except:print("VAE LOAD FAILED")# ===============================# LOAD MODEL# ===============================print("Loading AI model...")pipe = StableDiffusionPipeline.from_pretrained("SG161222/Realistic_Vision_V5.1_noVAE",cache_dir=CACHE_DIR,torch_dtype=torch.float32,safety_checker=None,vae=vae)pipe.enable_attention_slicing()6 unmodified linesapp = Flask(__name__)# ======================================================# WEB PANEL (TEST GENERATORA)# ======================================================HTML_PAGE = """<!DOCTYPE html><html><head><title>IMAGE PRO AI</title><style>body{font-family:Arial;background:#111;color:white;text-align:center;padding:40px}input{width:400px;padding:10px}button{padding:10px 20px;background:#ff6a00;border:none;color:white;font-size:16px}img{margin-top:20px;max-width:512px}</style></head><body><h1>IMAGE PRO AI</h1><form action="/generate_web" method="post"><input name="prompt" placeholder="Wpisz prompt (np. kot w butach)"><br><br><button type="submit">GENERUJ</button></form>{% if image %}<h2>Wynik</h2><img src="{{image}}">{% endif %}</body></html>"""@app.route("/", methods=["GET"])def home():return render_template_string(HTML_PAGE)# ======================================================# GENERATE FROM WEB PANEL# ======================================================@app.route("/generate_web", methods=["POST"])def generate_web():prompt = request.form["prompt"]prompt = translate_prompt(prompt)image = pipe(prompt,num_inference_steps=30,guidance_scale=7.5).images[0]path = OUTPUT_DIR + "/web_gen.png"image.save(path)return render_template_string(HTML_PAGE,image="/image/web_gen.png")@app.route("/image/<filename>")def serve_image(filename):return send_file(OUTPUT_DIR + "/" + filename, mimetype="image/png")# ======================================================# API GENERATE# ======================================================@app.route("/generate", methods=["POST"])def generate():8 unmodified lines).images[0]path = OUTPUT_DIR + "/gen.png"image.save(path)return send_file(path, mimetype="image/png")# ======================================================# PRODUCT AD# ======================================================@app.route("/product_ad", methods=["POST"])def product_ad():data = request.jsonprompt = translate_prompt(data["prompt"])style1 = prompt + ", luxury product photography, studio lighting"style2 = prompt + ", commercial advertising, dramatic lighting"img1 = pipe(style1).images[0]img2 = pipe(style2).images[0]p1 = OUTPUT_DIR + "/ad1.png"p2 = OUTPUT_DIR + "/ad2.png"img1.save(p1)img2.save(p2)return jsonify({"image1": p1,"image2": p2})# ======================================================# RESTORE PHOTO# ======================================================@app.route("/restore", methods=["POST"])def restore():1 unmodified linefile = request.files["image"]img = Image.open(file.stream)img = img.filter(ImageFilter.SHARPEN)path = OUTPUT_DIR + "/restored.png"2 unmodified linesreturn send_file(path, mimetype="image/png")# ======================================================# UPSCALE HD# ======================================================@app.route("/upscale", methods=["POST"])def upscale():2 unmodified linesimg = Image.open(file.stream)width, height = img.sizeimg = img.resize((width*2, height*2),Image.LANCZOS)path = OUTPUT_DIR + "/hd.png"1 unmodified linereturn send_file(path, mimetype="image/png")# ======================================================# COLORIZE# ======================================================@app.route("/colorize", methods=["POST"])def colorize():1 unmodified linefile = request.files["image"]img = Image.open(file.stream)img = img.convert("RGB")path = OUTPUT_DIR + "/color.png"2 unmodified linesreturn send_file(path, mimetype="image/png")# ======================================================# STUDIO PRO# ======================================================@app.route("/studio_pro", methods=["POST"])def studio_pro():data = request.jsonprompt = translate_prompt(data["prompt"])prompts = [prompt + ", luxury studio lighting",prompt + ", product on marble table",prompt + ", premium advertising photo",prompt + ", instagram product ad",prompt + ", minimal product photography"]results = []for p in prompts:img = pipe(p).images[0]path = OUTPUT_DIR + "/" + str(len(results)) + ".png"img.save(path)results.append(path)return jsonify(results)# ======================================================# START SERVER# ======================================================if __name__ == "__main__":print("IMAGE PRO API READY")app.run(host="0.0.0.0",port=7860,debug=False)123456789101112133 unmodified lines171819202122232 unmodified lines26272829303132333435363738394041426 unmodified lines4950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571588 unmodified lines1671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002011 unmodified line2032042052062072082092 unmodified lines2122132142152162172182192202 unmodified lines2232242252262272282292302311 unmodified line2332342352362372382392402411 unmodified line2432442452462472482492 unmodified lines252253254255256257258259260261262263264265266import osimport torchfrom flask import Flask, request, send_file, jsonify, render_template_stringfrom diffusers import StableDiffusionPipelinefrom PIL import Image, ImageFilterfrom deep_translator import GoogleTranslatorprint("IMAGE PRO AI STARTING...")CACHE_DIR = "./models"OUTPUT_DIR = "outputs"os.makedirs(OUTPUT_DIR, exist_ok=True)3 unmodified lines# ===============================def translate_prompt(prompt):try:prompt_en = GoogleTranslator(source="pl", target="en").translate(prompt)print("PL:", prompt)2 unmodified linesexcept:return prompt# ===============================# LOAD MODEL# ===============================print("Loading model...")pipe = StableDiffusionPipeline.from_pretrained("SG161222/Realistic_Vision_V5.1_noVAE",cache_dir=CACHE_DIR,torch_dtype=torch.float32,safety_checker=None)pipe.enable_attention_slicing()6 unmodified linesapp = Flask(__name__)# ===============================# HTML PANEL# ===============================HTML = """<html><head><title>IMAGE PRO AI</title><style>body{background:black;color:white;font-family:Arial;text-align:center;}input{width:400px;padding:10px;}button{padding:10px 20px;background:orange;border:none;color:white;font-size:16px;cursor:pointer;}img{margin-top:20px;max-width:512px;}</style></head><body><h1>IMAGE PRO AI</h1><input id="prompt" placeholder="np. truskawka na stole"/><br><br><button onclick="generate()">GENERUJ</button><h2>Wynik</h2><img id="result"/><script>async function generate(){prompt = document.getElementById("prompt").valueresponse = await fetch("/generate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({prompt:prompt})})blob = await response.blob()url = URL.createObjectURL(blob)document.getElementById("result").src = url}</script></body></html>"""# ===============================# HOME# ===============================@app.route("/")def home():return render_template_string(HTML)# ===============================# GENERATE IMAGE# ===============================@app.route("/generate", methods=["POST"])def generate():8 unmodified lines).images[0]path = OUTPUT_DIR + "/gen.png"image.save(path)return send_file(path, mimetype="image/png")# ===============================# PRODUCT AD# ===============================@app.route("/product_ad", methods=["POST"])def product_ad():data = request.jsonprompt = translate_prompt(data["prompt"])style = prompt + ", luxury product photography"image = pipe(style).images[0]path = OUTPUT_DIR + "/product.png"image.save(path)return send_file(path, mimetype="image/png")# ===============================# RESTORE PHOTO# ===============================@app.route("/restore", methods=["POST"])def restore():1 unmodified linefile = request.files["image"]img = Image.open(file.stream)img = img.filter(ImageFilter.SHARPEN)path = OUTPUT_DIR + "/restored.png"2 unmodified linesreturn send_file(path, mimetype="image/png")# ===============================# UPSCALE# ===============================@app.route("/upscale", methods=["POST"])def upscale():2 unmodified linesimg = Image.open(file.stream)w,h = img.sizeimg = img.resize((w*2,h*2), Image.LANCZOS)path = OUTPUT_DIR + "/hd.png"1 unmodified linereturn send_file(path, mimetype="image/png")# ===============================# COLORIZE# ===============================@app.route("/colorize", methods=["POST"])def colorize():1 unmodified linefile = request.files["image"]img = Image.open(file.stream)img = img.convert("RGB")path = OUTPUT_DIR + "/color.png"2 unmodified linesreturn send_file(path, mimetype="image/png")# ===============================# START SERVER# ===============================if __name__ == "__main__":print("SERVER READY")app.run(host="0.0.0.0",port=7860)
api.py+110-145