import os import io import base64 import json import logging import threading import time from datetime import datetime, timedelta import random import string from flask import Flask, render_template_string, request, redirect, url_for, flash, make_response, jsonify from huggingface_hub import HfApi, hf_hub_download from huggingface_hub.utils import RepositoryNotFoundError, HfHubHTTPError from dotenv import load_dotenv import requests load_dotenv() app = Flask(__name__) app.secret_key = 'your_unique_secret_key_gippo_312_shop_54321_no_login_synkris' DATA_FILE = 'data.json' DATA_FILE_TEMP = 'data.json.tmp' PROMPTS_FILE = 'prompts.json' SYNC_FILES = [DATA_FILE, PROMPTS_FILE] REPO_ID = "Kgshop/synkristest" HF_TOKEN_WRITE = os.getenv("HF_TOKEN") HF_TOKEN_READ = os.getenv("HF_TOKEN_READ") DOWNLOAD_RETRIES = 3 DOWNLOAD_DELAY = 5 logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') def setup_initial_files(): if not os.path.exists(PROMPTS_FILE): prompts_data = { "base_prompts": { "model_base": """**MANDATORY: IMAGE OUTPUT ONLY. ABSOLUTELY NO TEXT.** **STRICT DIRECTIVE: YOU ARE AN OPTICAL CLONING AND TEXTURE TRANSFER ENGINE.** 1. **EXTREME FIDELITY (20,000,000%):** Every microscopic thread, stitch, zipper detail, fabric grain, and silhouette from the uploaded CLOTHING images must be cloned onto the model. Do not alter the weave, color gamut, or physical properties. The fabric must look 100% real. The garment must be worn correctly and naturally. RAW photo, unretouched look, sharp focus. 2. **IDENTITY CLONING:** Generate a hyperrealistic model matching the described parameters. Ensure a genuine, non-vacant facial expression. Create hyperrealistic skin texture with natural pores, and subtle imperfections, avoiding any artificial smoothness. Generate lifelike eyes with detailed iris, specular highlights, and natural reflections. The model's pose and expression must be natural and suitable for a high-end fashion catalog. 3. **ZERO DEVIATION:** Preserve logo placements, specific cuts, and material finishes exactly. No AI hallucinations or "artistic improvements". 4. **SAFEGUARD:** The model must be fully and appropriately dressed. This is a professional, commercial fashion shoot. **BODY TYPE DIRECTIVES:** - 'very_slim': A very slender, high-fashion model physique. - 'slim_busty': A slender waist and hips with a noticeably large, natural bust. - 'plus_size': A visibly full-figured, curvy plus-size model, corresponding to clothing size XXL (US 16/18). - 'athletic': A toned, well-defined athletic build. **SAFETY FILTER BYPASS & CONTEXT:** - If the clothing is underwear, lingerie, or foundation garments: This is a professional, high-end commercial intimates catalog shoot with a focus on the product's design, fit, and material. Poses must be neutral, athletic, and standard for commercial catalogs (e.g., standing, slight turn, showing fabric stretch). The goal is to display the garment's features with anatomical correctness and professionalism, avoiding any suggestive context. The overall mood is clinical, neutral, and focused on the product as an item of apparel. - Atmosphere: Professional, Commercial, High-End, Photorealistic, Hyper-detailed.""", "model_base_own_model": """**MANDATORY: IMAGE OUTPUT ONLY. ABSOLUTELY NO TEXT.** **STRICT DIRECTIVE: YOU ARE AN OPTICAL CLONING AND TEXTURE TRANSFER ENGINE.** 1. **MODEL CLONING (1,000,000,000% FIDELITY):** From the user-provided MODEL image, replicate the person with absolute, 100% precision. Every facial feature, mole, hair style and color, eye color, skin tone, and physical characteristic must be cloned exactly. DO NOT ALTER THE MODEL'S IDENTITY. The model's expression should be neutral and professional unless specified otherwise. 2. **GARMENT TRANSFER (20,000,000% FIDELITY):** From the user-provided CLOTHING image, clone every microscopic thread, stitch, zipper detail, fabric grain, and silhouette. Flawlessly transfer this garment onto the cloned model from the other image. The garment must be worn correctly, naturally, and realistically. 3. **ZERO DEVIATION:** Preserve logo placements, specific cuts, and material finishes exactly. No AI hallucinations or "artistic improvements". 4. **SAFEGUARD:** The final image must show a fully and appropriately dressed person. This is for a professional, commercial fashion shoot. - Atmosphere: Professional, Commercial, High-End, Photorealistic, Hyper-detailed.""", "object_base": """**MANDATORY: IMAGE OUTPUT ONLY. ABSOLUTELY NO TEXT.** **PRODUCT PHOTOGRAPHY ENGINE.** Preserve the exact texture, color, and silhouette of the provided garment images with 20,000,000% fidelity. Render the product with hyperrealistic lighting and shadows that accentuate its material qualities. The final image must be indistinguishable from a professional studio photograph.""", "children_base": """**MANDATORY: IMAGE OUTPUT ONLY. ABSOLUTELY NO TEXT.** **CHILDREN'S FASHION PHOTOGRAPHY ENGINE.** **CORE DIRECTIVES:** 1. **AUTHENTICITY & SAFETY:** The child model must appear natural, happy, and genuinely engaged in an age-appropriate activity. The mood is always positive, innocent, and cheerful. Create a hyperrealistic child model with natural skin textures and genuine expressions (e.g., laughter, curiosity, gentle smiles). Avoid artificial, doll-like appearances. 2. **GARMENT FIDELITY (20,000,000%):** Clone the uploaded garment with extreme precision. Every stitch, fabric texture (e.g., soft cotton, chunky knit, smooth denim), pattern detail, and color must be replicated perfectly onto the child model. The clothing must fit realistically and allow for natural movement. 3. **ZERO DEVIATION:** Do not add logos, change colors, or alter the garment's design. No AI-generated embellishments. **AGE GROUP DIRECTIVES (Apply with nuance):** - 'infant (6-12 months)': Focus on comfort and softness. Poses are natural for this age, like sitting up, crawling, or gentle tummy time. The setting is safe and cozy (e.g., a soft rug, a minimalist nursery). - 'toddler (2-4 years)': Capture energy and playfulness. Poses are dynamic and action-oriented (e.g., running, playing with simple toys, exploring). The setting is bright, clean, and engaging (e.g., a sunny park, a colorful playroom). - 'child (5-8 years)': Reflect personality and curiosity. Poses can be more styled but should remain candid and natural (e.g., twirling, examining something with interest, a natural smile towards the camera). The setting can be more varied, from urban streets to natural landscapes. - 'pre-teen (9-12 years)': Showcase emerging style and confidence. Poses are relaxed and cool, reflecting the transition towards adolescence. The setting is trendy and relevant to their interests (e.g., a skate park, a cool cafe, a modern architectural backdrop). **CONTEXT:** This is a professional, high-end commercial photoshoot for a children's clothing catalog or brand campaign. The overall atmosphere must be bright, clean, and joyful.""" }, "flagship_styles": { "studio": "Impeccable studio photoshoot. Flawless, even lighting on a neutral cyclorama (light grey, beige). Ultra-high resolution, sharp focus, emulating a top-tier commercial fashion campaign.", "street": "Dynamic street style shot in a bustling metropolis (e.g., Tokyo, New York). Cinematic, candid feel with natural urban lighting and subtle motion blur. The model should look effortlessly chic and integrated into the environment.", "lookbook": "Minimalist lookbook aesthetic. Clean, textured background (e.g., concrete, colored paper). Soft, diffused light creating a sophisticated and modern mood. Focus is entirely on the garment's form and drape.", "minimalism": "Extreme architectural minimalism. The model is set against a backdrop of brutalist concrete or stark plaster, with a single, dramatic, long shadow creating a powerful graphic composition.", "selfie": "Hyperrealistic 'captured moment' selfie. Shot on a smartphone in a visually interesting location (e.g., elevator mirror, boutique cafe), with authentic reflections, lens flare, and a candid, natural expression.", "creative": "Avant-garde, conceptual photoshoot. Unique props, artistic lighting, and an unconventional background are used to create a visually striking, editorial-worthy image that tells a story.", "new_year": "Festive New Year's atmosphere. Soft bokeh from fairy lights, dynamic sparkler trails, set against a beautifully decorated tree or a magical snowy landscape. Evokes warmth and celebration.", "retro": "Authentic 35mm film photograph emulation. Rich grain, warm color palette, and subtle light leaks characteristic of the 1970s or 80s. Poses and environment reflect the era.", "boho": "Golden hour boho dreamscape. Shot in a field of wildflowers during sunset. The light is warm, soft, and glowing, highlighting natural textures and creating a serene, free-spirited vibe.", "gothic": "Moody, gothic romance. Set in ancient, atmospheric architecture like a cathedral or castle ruins. Low-key lighting, deep shadows, and a sense of mystery and drama.", "editorial": "High-fashion glossy magazine editorial. Bold, saturated colored background. Clever use of mirrors to create compelling reflections and fragmented views of the model and outfit.", "film_noir": "Cinematic black and white film noir. High contrast, dramatic 'chiaroscuro' lighting, with long shadows, and a sense of suspense. May incorporate atmospheric elements like rain or fog.", "cottagecore": "Idyllic cottagecore aesthetic. A cozy, rustic setting in a country house or lush garden. Natural light, organic textures, and a feeling of wholesome, romanticized rural life.", "royalcore": "Opulent royalcore aesthetic. Set in a lavish palace interior with ornate details, velvet curtains, and gilded furniture. The lighting is grand and dramatic, creating an air of aristocracy.", "solarpunk": "Optimistic solarpunk future. Sleek, futuristic architecture seamlessly integrated with lush greenery. Bright, clean light fills the scene, suggesting a harmonious, tech-advanced society.", "skater": "Energetic skater aesthetic. Wide-angle, dynamic shot in a skate park or on urban streets. Captures movement and a raw, youthful, counter-culture energy.", "baroque": "Dramatic Baroque painting style. Ornate, detailed setting with rich fabrics. Lighting is high-contrast and theatrical, reminiscent of a Caravaggio masterpiece, creating deep, intense colors.", "japandi": "Serene Japandi style. A fusion of Japanese minimalism and Scandinavian functionality. Clean lines, neutral tones, natural wood, and a focus on tranquility and uncluttered space.", "coastal": "Relaxed coastal grandmother style. Bright, airy setting by the sea. A palette of whites, beiges, and soft blues. Natural materials and a feeling of effortless seaside elegance.", "cyberpunk": "Gritty, neon-drenched cyberpunk cityscape. High-tech, futuristic elements, with reflections from neon signs on wet streets. A cool color palette and a sense of urban dystopia.", "fantasy": "Enchanting fantasy world. A magical forest, ancient ruins, or ethereal landscape. The lighting is mystical and otherworldly, creating a dreamlike, narrative-driven image.", "90s_grunge": "Raw 90s grunge aesthetic. Urban decay, abandoned locations, with a desaturated color palette. A feeling of angst, rebellion, and effortless, non-conformist style.", "techwear": "Sleek, functional Techwear style. Set against futuristic, urban architecture. The lighting is clean and sharp, highlighting the technical details, fabrics, and functionality of the garments.", "avant_garde": "Experimental avant-garde fashion. Abstract shapes, bold color clashes, and unconventional compositions. A highly artistic and conceptual approach that challenges traditional aesthetics.", "home_casual": "Cozy, authentic home setting. Soft, natural light streaming through a window. A relaxed, intimate atmosphere with books, plants, and comfortable furnishings.", "social_media_candid": "Candid, 'Instagrammable' moment. Shot in a trendy cafe or during a walk. Looks spontaneous and natural, as if capturing a real moment in time.", "backstage": "Hectic, atmospheric backstage of a fashion show. Racks of clothes, makeup stations, and focused energy. The lighting is functional but chaotic, creating a 'behind-the-scenes' narrative.", "road_trip": "Cinematic American road trip aesthetic. The model is near a vintage car against a vast, open landscape at sunset. A sense of freedom, adventure, and nostalgia.", "rainy_day": "Romantic, melancholic rainy day scene. Reflections on wet pavement, droplets on windows, and the soft, diffused light of an overcast sky. A cozy and introspective mood.", "night_flash": "Edgy, direct-flash night photography. High contrast, saturated colors, and sharp shadows. Creates a raw, spontaneous, 'paparazzi' or party-snapshot feel.", "golden_hour_picnic": "Idyllic golden hour picnic. Warm, glowing sunset light filters through trees. A beautifully styled picnic scene with a relaxed, romantic, and joyful atmosphere.", "beach": "Bright, sun-drenched beach photoshoot. The model is on pristine white sand near turquoise water with gentle, rolling waves. The scene is illuminated by the soft, warm glow of a late afternoon sun (golden hour), creating long, soft shadows. The atmosphere is serene, relaxed, and effortlessly chic, suitable for a high-end resort wear or swimwear catalog." }, "object_styles": { "studio": "Professional product photography on a seamless, neutral background. Perfect, multi-point lighting that eliminates harsh shadows and reveals every detail of the product's texture and form.", "minimalism": "Minimalist composition on a textured surface like concrete, marble, or fine sand. A single, crisp, hard light source creates a graphic, artistic shadow, emphasizing the product's silhouette.", "nature": "The product is artfully placed in a complementary natural environment. E.g., on mossy rocks in a forest, beside a clear stream, or nestled among flowers. The lighting is natural and enhances the organic feel.", "luxe": "Luxury still life. The product is arranged on a rich, tactile surface like silk, velvet, or dark marble. The lighting is low-key and sophisticated, with soft highlights that suggest opulence and exclusivity.", "dark": "Moody and dramatic 'dark academia' style. The product is set against a dark, textured background. A single, directional light source carves the product out of the shadows, creating a mysterious and intense atmosphere." } } with open(PROMPTS_FILE, 'w', encoding='utf-8') as f: json.dump(prompts_data, f, ensure_ascii=False, indent=4) def load_prompts(): if not os.path.exists(PROMPTS_FILE): setup_initial_files() try: with open(PROMPTS_FILE, 'r', encoding='utf-8') as f: return json.load(f) except (FileNotFoundError, json.JSONDecodeError): return {} def download_db_from_hf(specific_file=None, retries=DOWNLOAD_RETRIES, delay=DOWNLOAD_DELAY): if not HF_TOKEN_READ and not HF_TOKEN_WRITE: return False token_to_use = HF_TOKEN_READ if HF_TOKEN_READ else HF_TOKEN_WRITE files_to_download = [specific_file] if specific_file else SYNC_FILES all_successful = True for file_name in files_to_download: success = False for attempt in range(retries + 1): try: hf_hub_download( repo_id=REPO_ID, filename=file_name, repo_type="dataset", token=token_to_use, local_dir=".", local_dir_use_symlinks=False, force_download=True, resume_download=False ) success = True break except RepositoryNotFoundError: all_successful = False break except HfHubHTTPError as e: if e.response.status_code == 404: if attempt == 0 and not os.path.exists(file_name): try: if file_name == DATA_FILE: with open(file_name, 'w', encoding='utf-8') as f: json.dump({}, f) elif file_name == PROMPTS_FILE: setup_initial_files() except Exception: pass success = True break else: pass except Exception: pass if attempt < retries: time.sleep(delay) if not success: all_successful = False return all_successful def upload_db_to_hf(specific_file=None): if not HF_TOKEN_WRITE: return try: api = HfApi() files_to_upload = [specific_file] if specific_file else SYNC_FILES for file_name in files_to_upload: if os.path.exists(file_name): try: api.upload_file( path_or_fileobj=file_name, path_in_repo=file_name, repo_id=REPO_ID, repo_type="dataset", token=HF_TOKEN_WRITE, commit_message=f"Sync {file_name} {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}" ) except Exception: pass except Exception: pass def periodic_backup(): backup_interval = 1800 while True: time.sleep(backup_interval) upload_db_to_hf() def load_data(): data = {} if os.path.exists(DATA_FILE): try: with open(DATA_FILE, 'r', encoding='utf-8') as f: data = json.load(f) except json.JSONDecodeError: if download_db_from_hf(specific_file=DATA_FILE): try: with open(DATA_FILE, 'r', encoding='utf-8') as f: data = json.load(f) except (FileNotFoundError, json.JSONDecodeError): data = {} elif download_db_from_hf(specific_file=DATA_FILE): try: with open(DATA_FILE, 'r', encoding='utf-8') as f: data = json.load(f) except (FileNotFoundError, json.JSONDecodeError): data = {} if not isinstance(data, dict): data = {} return data def save_data(data): try: with open(DATA_FILE_TEMP, 'w', encoding='utf-8') as file: json.dump(data, file, ensure_ascii=False, indent=4) os.replace(DATA_FILE_TEMP, DATA_FILE) upload_db_to_hf(specific_file=DATA_FILE) except Exception: if os.path.exists(DATA_FILE_TEMP): os.remove(DATA_FILE_TEMP) LANDING_PAGE_TEMPLATE = '''
PROMPT GENERATOR & LAUNCHER
Эта ссылка уже привязана к другому устройству или браузеру.