Update app.py
Browse files
app.py
CHANGED
|
@@ -3,104 +3,46 @@ import sys
|
|
| 3 |
import io
|
| 4 |
import logging
|
| 5 |
from pathlib import Path
|
| 6 |
-
from datetime import datetime
|
| 7 |
from flask import Flask, request, send_file, jsonify
|
| 8 |
-
from PIL import Image
|
| 9 |
import torch
|
| 10 |
-
import torchvision.transforms as transforms
|
| 11 |
from database import init_db, close_db, get_db_path
|
| 12 |
|
| 13 |
-
# Proje
|
| 14 |
sys.path.insert(0, str(Path(__file__).parent))
|
| 15 |
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
from demo_generate.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
|
| 20 |
-
#
|
| 21 |
os.environ['NUMBA_DISABLE_JIT'] = '1'
|
| 22 |
os.environ['TORCH_HOME'] = '/tmp/torch_cache'
|
| 23 |
os.environ['U2NET_HOME'] = '/tmp/.u2net'
|
| 24 |
|
| 25 |
-
#
|
| 26 |
os.makedirs('/tmp/torch_cache', exist_ok=True)
|
| 27 |
os.makedirs('/tmp/.u2net', exist_ok=True)
|
| 28 |
|
| 29 |
-
#
|
| 30 |
logging.basicConfig(level=logging.INFO)
|
| 31 |
logger = logging.getLogger(__name__)
|
| 32 |
|
| 33 |
-
#
|
| 34 |
app = Flask(__name__)
|
| 35 |
init_db(app)
|
| 36 |
|
| 37 |
-
#
|
| 38 |
-
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 39 |
-
|
| 40 |
-
# AnimeGAN model yükleme (orijinal kodunuz aynen korundu)
|
| 41 |
-
try:
|
| 42 |
-
logger.info("Loading AnimeGAN model...")
|
| 43 |
-
model = torch.hub.load(
|
| 44 |
-
'bryandlee/animegan2-pytorch:main',
|
| 45 |
-
'generator',
|
| 46 |
-
pretrained='face_paint_512_v2',
|
| 47 |
-
trust_repo=True
|
| 48 |
-
).to(device)
|
| 49 |
-
model.eval()
|
| 50 |
-
logger.info("Model loaded successfully")
|
| 51 |
-
except Exception as e:
|
| 52 |
-
logger.error(f"Model loading failed: {str(e)}")
|
| 53 |
-
raise
|
| 54 |
-
|
| 55 |
-
# --- Image Processing Functions ---
|
| 56 |
-
def process_image(image):
|
| 57 |
-
"""Convert image to anime style"""
|
| 58 |
-
transform = transforms.Compose([
|
| 59 |
-
transforms.Resize((512, 512)),
|
| 60 |
-
transforms.ToTensor(),
|
| 61 |
-
transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
|
| 62 |
-
])
|
| 63 |
-
with torch.no_grad():
|
| 64 |
-
output = model(transform(image).unsqueeze(0).to(device))
|
| 65 |
-
return transforms.ToPILImage()((output * 0.5 + 0.5).squeeze().cpu())
|
| 66 |
-
|
| 67 |
-
def remove_background_original(image_data): # İsim değiştirildi
|
| 68 |
-
"""Remove image background"""
|
| 69 |
-
from rembg import remove
|
| 70 |
-
input_image = Image.open(io.BytesIO(image_data))
|
| 71 |
-
if input_image.mode != 'RGB':
|
| 72 |
-
input_image = input_image.convert('RGB')
|
| 73 |
-
return remove(input_image)
|
| 74 |
-
|
| 75 |
-
# --- API Routes ---
|
| 76 |
@app.route('/')
|
| 77 |
def home():
|
| 78 |
-
return "Anime
|
| 79 |
-
|
| 80 |
-
# Yeni eklenen endpoint: /generate-v2
|
| 81 |
-
@app.route('/generate-v2', methods=['POST'])
|
| 82 |
-
def generate_v2():
|
| 83 |
-
try:
|
| 84 |
-
if 'image' not in request.files:
|
| 85 |
-
return jsonify({'error': 'Resim yüklenmedi'}), 400
|
| 86 |
-
|
| 87 |
-
file = request.files['image']
|
| 88 |
-
if not file.filename:
|
| 89 |
-
return jsonify({'error': 'Boş dosya'}), 400
|
| 90 |
|
| 91 |
-
|
| 92 |
-
processed_img = apply_animegan(image) # Yeni modül kullanılıyor
|
| 93 |
-
|
| 94 |
-
img_io = io.BytesIO()
|
| 95 |
-
processed_img.save(img_io, 'PNG')
|
| 96 |
-
img_io.seek(0)
|
| 97 |
-
return send_file(img_io, mimetype='image/png')
|
| 98 |
-
|
| 99 |
-
except Exception as e:
|
| 100 |
-
logger.error(f"Hata: {str(e)}")
|
| 101 |
-
return jsonify({'error': str(e)}), 500
|
| 102 |
-
|
| 103 |
-
# Orijinal endpoint'ler aynen korundu
|
| 104 |
@app.route('/generate', methods=['POST'])
|
| 105 |
def generate():
|
| 106 |
try:
|
|
@@ -109,10 +51,10 @@ def generate():
|
|
| 109 |
|
| 110 |
file = request.files['image']
|
| 111 |
if not file.filename:
|
| 112 |
-
return jsonify({'error': '
|
| 113 |
|
| 114 |
image = Image.open(io.BytesIO(file.read())).convert("RGB")
|
| 115 |
-
processed_img =
|
| 116 |
|
| 117 |
img_io = io.BytesIO()
|
| 118 |
processed_img.save(img_io, 'PNG')
|
|
@@ -121,34 +63,9 @@ def generate():
|
|
| 121 |
|
| 122 |
except Exception as e:
|
| 123 |
logger.error(f"Hata: {str(e)}")
|
| 124 |
-
return jsonify({'error':
|
| 125 |
|
| 126 |
-
#
|
| 127 |
-
@app.route('/remove-bg-v2', methods=['POST'])
|
| 128 |
-
def bg_remove_v2():
|
| 129 |
-
try:
|
| 130 |
-
if 'image' not in request.files:
|
| 131 |
-
return jsonify({'error': 'Resim yüklenmedi'}), 400
|
| 132 |
-
|
| 133 |
-
file = request.files['image']
|
| 134 |
-
file.seek(0, os.SEEK_END)
|
| 135 |
-
file_size = file.tell()
|
| 136 |
-
file.seek(0)
|
| 137 |
-
|
| 138 |
-
if file_size > 10 * 1024 * 1024:
|
| 139 |
-
return jsonify({'error': 'Dosya boyutu 10MB üzerinde'}), 400
|
| 140 |
-
|
| 141 |
-
output = remove_background(file.read()) # Yeni modül kullanılıyor
|
| 142 |
-
img_io = io.BytesIO()
|
| 143 |
-
output.save(img_io, 'PNG')
|
| 144 |
-
img_io.seek(0)
|
| 145 |
-
return send_file(img_io, mimetype='image/png')
|
| 146 |
-
|
| 147 |
-
except Exception as e:
|
| 148 |
-
logger.error(f"Arkaplan kaldırma hatası: {str(e)}")
|
| 149 |
-
return jsonify({'error': str(e)}), 500
|
| 150 |
-
|
| 151 |
-
# Orijinal endpoint aynen korundu
|
| 152 |
@app.route('/remove-bg', methods=['POST'])
|
| 153 |
def bg_remove():
|
| 154 |
try:
|
|
@@ -156,14 +73,10 @@ def bg_remove():
|
|
| 156 |
return jsonify({'error': 'Resim yüklenmedi'}), 400
|
| 157 |
|
| 158 |
file = request.files['image']
|
| 159 |
-
file.
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
if file_size > 10 * 1024 * 1024:
|
| 164 |
-
return jsonify({'error': 'Dosya boyutu 10MB üzerinde'}), 400
|
| 165 |
-
|
| 166 |
-
output = remove_background_original(file.read())
|
| 167 |
img_io = io.BytesIO()
|
| 168 |
output.save(img_io, 'PNG')
|
| 169 |
img_io.seek(0)
|
|
@@ -173,7 +86,7 @@ def bg_remove():
|
|
| 173 |
logger.error(f"Arkaplan kaldırma hatası: {str(e)}")
|
| 174 |
return jsonify({'error': str(e)}), 500
|
| 175 |
|
| 176 |
-
#
|
| 177 |
@app.route('/halftone', methods=['POST'])
|
| 178 |
def halftone_route():
|
| 179 |
try:
|
|
@@ -196,7 +109,7 @@ def halftone_route():
|
|
| 196 |
logger.error(f"Halftone hatası: {str(e)}")
|
| 197 |
return jsonify({'error': str(e)}), 500
|
| 198 |
|
| 199 |
-
#
|
| 200 |
@app.route('/users', methods=['GET'])
|
| 201 |
def get_users_route():
|
| 202 |
from get_methods import get_users
|
|
@@ -217,7 +130,7 @@ def consume_user_route(udid):
|
|
| 217 |
from consume_method import consume_user
|
| 218 |
return consume_user(udid)
|
| 219 |
|
| 220 |
-
#
|
| 221 |
@app.teardown_appcontext
|
| 222 |
def shutdown_session(exception=None):
|
| 223 |
close_db()
|
|
|
|
| 3 |
import io
|
| 4 |
import logging
|
| 5 |
from pathlib import Path
|
|
|
|
| 6 |
from flask import Flask, request, send_file, jsonify
|
| 7 |
+
from PIL import Image
|
| 8 |
import torch
|
|
|
|
| 9 |
from database import init_db, close_db, get_db_path
|
| 10 |
|
| 11 |
+
# Proje yolu ayarı
|
| 12 |
sys.path.insert(0, str(Path(__file__).parent))
|
| 13 |
|
| 14 |
+
# Modül importları
|
| 15 |
+
try:
|
| 16 |
+
from demo_generate.halftone_method import apply_halftone
|
| 17 |
+
from demo_generate.animegan_method import apply_animegan
|
| 18 |
+
from demo_generate.rembg_method import remove_background
|
| 19 |
+
except ImportError as e:
|
| 20 |
+
logging.error(f"Modül import hatası: {e}")
|
| 21 |
+
raise
|
| 22 |
|
| 23 |
+
# Ortam ayarları
|
| 24 |
os.environ['NUMBA_DISABLE_JIT'] = '1'
|
| 25 |
os.environ['TORCH_HOME'] = '/tmp/torch_cache'
|
| 26 |
os.environ['U2NET_HOME'] = '/tmp/.u2net'
|
| 27 |
|
| 28 |
+
# Önbellek klasörleri
|
| 29 |
os.makedirs('/tmp/torch_cache', exist_ok=True)
|
| 30 |
os.makedirs('/tmp/.u2net', exist_ok=True)
|
| 31 |
|
| 32 |
+
# Log ayarı
|
| 33 |
logging.basicConfig(level=logging.INFO)
|
| 34 |
logger = logging.getLogger(__name__)
|
| 35 |
|
| 36 |
+
# Flask uygulaması
|
| 37 |
app = Flask(__name__)
|
| 38 |
init_db(app)
|
| 39 |
|
| 40 |
+
# Ana sayfa
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
@app.route('/')
|
| 42 |
def home():
|
| 43 |
+
return "Anime İşleme API - Çalışıyor"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
|
| 45 |
+
# Anime dönüştürme
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
@app.route('/generate', methods=['POST'])
|
| 47 |
def generate():
|
| 48 |
try:
|
|
|
|
| 51 |
|
| 52 |
file = request.files['image']
|
| 53 |
if not file.filename:
|
| 54 |
+
return jsonify({'error': 'Geçersiz dosya'}), 400
|
| 55 |
|
| 56 |
image = Image.open(io.BytesIO(file.read())).convert("RGB")
|
| 57 |
+
processed_img = apply_animegan(image)
|
| 58 |
|
| 59 |
img_io = io.BytesIO()
|
| 60 |
processed_img.save(img_io, 'PNG')
|
|
|
|
| 63 |
|
| 64 |
except Exception as e:
|
| 65 |
logger.error(f"Hata: {str(e)}")
|
| 66 |
+
return jsonify({'error': 'İşlem sırasında hata oluştu'}), 500
|
| 67 |
|
| 68 |
+
# Arkaplan kaldırma
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
@app.route('/remove-bg', methods=['POST'])
|
| 70 |
def bg_remove():
|
| 71 |
try:
|
|
|
|
| 73 |
return jsonify({'error': 'Resim yüklenmedi'}), 400
|
| 74 |
|
| 75 |
file = request.files['image']
|
| 76 |
+
if file.filename == '':
|
| 77 |
+
return jsonify({'error': 'Boş dosya'}), 400
|
| 78 |
+
|
| 79 |
+
output = remove_background(file.read())
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
img_io = io.BytesIO()
|
| 81 |
output.save(img_io, 'PNG')
|
| 82 |
img_io.seek(0)
|
|
|
|
| 86 |
logger.error(f"Arkaplan kaldırma hatası: {str(e)}")
|
| 87 |
return jsonify({'error': str(e)}), 500
|
| 88 |
|
| 89 |
+
# Halftone efekti
|
| 90 |
@app.route('/halftone', methods=['POST'])
|
| 91 |
def halftone_route():
|
| 92 |
try:
|
|
|
|
| 109 |
logger.error(f"Halftone hatası: {str(e)}")
|
| 110 |
return jsonify({'error': str(e)}), 500
|
| 111 |
|
| 112 |
+
# Veritabanı işlemleri
|
| 113 |
@app.route('/users', methods=['GET'])
|
| 114 |
def get_users_route():
|
| 115 |
from get_methods import get_users
|
|
|
|
| 130 |
from consume_method import consume_user
|
| 131 |
return consume_user(udid)
|
| 132 |
|
| 133 |
+
# Kapatma
|
| 134 |
@app.teardown_appcontext
|
| 135 |
def shutdown_session(exception=None):
|
| 136 |
close_db()
|