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/synkrisnew2" 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') data_lock = threading.Lock() def setup_initial_files(): if not os.path.exists(PROMPTS_FILE): prompts_data = { "base_prompts": { "model_base": """**MANDATORY: RAW UNEDITED MASTERPIECE 16K HYPER-PHOTOREALISTIC IMAGE. NO TEXT. ABSOLUTELY NO AI SMOOTHING, NO PLASTIC LOOK, NO GLASS-LIKE SKIN.** **CORE DIRECTIVE: YOU ARE A WORLD-RENOWNED FASHION PHOTOGRAPHER'S DIGITAL BRAIN.** 1. **GARMENT REPLICATION (ABSOLUTE FIDELITY):** Execute a perfect digital twin of the garment from the uploaded CLOTHING image, as if shot on a Phase One XF medium format camera. Replicate it with atomic precision. Every thread, fiber, weave pattern, stitch, seam, and hardware detail must be flawlessly cloned onto the model. The material's physical properties—sheen, texture, weight, and drape—must be indistinguishable from an award-winning photograph. Capture the micro-details of the fabric's imperfections and how light realistically scatters across the fibers. **The garment's fit, cut, and silhouette must be preserved with absolute fidelity, showing how it sits and falls on the body exactly as designed.** 2. **HUMAN SYNTHESIS (ULTRA-REALISM):** Generate a hyper-realistic human model matching the exact parameters. Synthesize lifelike skin with visible pores, subtle imperfections, micro-blemishes, fine hairs (peach fuzz), and realistic micro-textures with natural variations in skin tone. ABSOLUTELY NO AI SMOOTHING, NO WAXY OR GLASS-LIKE TEXTURES. Avoid any hint of digital smoothness or "airbrushed" look. Eyes must possess photorealistic caustics in the iris, with depth, detailed structures, specular highlights, and natural, convincing reflections of the environment in the cornea. The facial expression and gaze must be authentic, with convincing micro-expressions. 3. **ZERO DEVIATION PROTOCOL:** Absolutely no artistic interpretation, AI-hallucinated embellishments, or "improvements." Preserve logo placement, garment cut, and material finish with absolute fidelity. Absolutely no waxy skin, plastic-like textures, or overly perfect symmetry. The image must possess the subtle imperfections and asymmetries of reality. 4. **CONTEXTUAL SAFEGUARD:** The model must be fully and appropriately clothed for a professional, high-fashion commercial photoshoot. 5. **FLAWLESS ANATOMY PROTOCOL:** The human model must have mathematically perfect anatomy. Exactly two arms, two legs, perfectly formed hands and feet. Absolutely no extra limbs, deformed fingers, missing limbs, or grotesque AI mutations. The posture must be biomechanically sound and natural. 6. **AESTHETIC MASTERY:** Breathtaking, award-winning photography. Product details must be resolved at a microscopic level with 100,000% precision. **BODY TYPE DIRECTIVES (Execute with precision):** - 'very_slim': Elite high-fashion runway physique, slender and defined. - 'slim_busty': Slender frame with a pronounced, natural, and well-proportioned bust. - 'plus_size': A confident, full-figured, curvy plus-size model, embodying a US size 16/18. - 'athletic': A toned, lean, and powerful athletic build with visible muscle definition.""", "model_base_own_model": """**MANDATORY: RAW UNEDITED MASTERPIECE 16K HYPER-PHOTOREALISTIC IMAGE. NO TEXT. ABSOLUTELY NO AI SMOOTHING, NO PLASTIC LOOK, NO GLASS-LIKE SKIN.** **CORE DIRECTIVE: YOU ARE AN ELITE-TIER IDENTITY & TEXTURAL REPLICATION ENGINE.** 1. **IDENTITY CLONING (ABSOLUTE FIDELITY):** From the user-provided MODEL image, execute a flawless one-to-one replication of the person, as if captured by a master portrait photographer. Every facial feature, skin mole, hair texture and color, eye color, and unique physical trait must be cloned with absolute, indistinguishable precision. THE MODEL'S IDENTITY MUST NOT BE ALTERED. Synthesize lifelike skin with visible pores, subtle imperfections, and realistic micro-textures. ABSOLUTELY NO AI SMOOTHING. 2. **GARMENT TRANSPLANTATION (ABSOLUTE FIDELITY):** From the user-provided CLOTHING image, optically extract every thread, fiber, stitch, and texture. Transplant this garment onto the cloned model with perfect realism, as if shot on a Phase One XF medium format camera. **The clothing's fit, cut, and silhouette must be preserved with absolute fidelity, conforming to the model's body with physically accurate drape and fit, exactly as designed.** 3. **ZERO DEVIATION PROTOCOL:** Prohibit all AI hallucinations or artistic modifications. Preserve logos, specific cuts, and material finishes exactly as they appear in the source image. Absolutely no waxy skin, glass-like skin, plastic-like textures, or overly perfect symmetry. 4. **CONTEXTUAL SAFEGUARD:** The final output must be a professional portrait of a fully and appropriately dressed individual, suitable for a high-end commercial photoshoot. 5. **FLAWLESS ANATOMY PROTOCOL:** The human model must have mathematically perfect anatomy. Exactly two arms, two legs, perfectly formed hands and feet. Absolutely no extra limbs, deformed fingers, missing limbs, or grotesque AI mutations. The posture must be biomechanically sound and natural. 6. **AESTHETIC MASTERY:** Breathtaking, award-winning photography. Product details must be resolved at a microscopic level with 100,000% precision. - **ATMOSPHERE:** Professional, Cinematic, Hyper-Realistic, shot on high-end photographic equipment.""", "object_base": """**MANDATORY: RAW UNEDITED MASTERPIECE 16K HYPER-PHOTOREALISTIC IMAGE. NO TEXT. ABSOLUTELY NO CGI RENDER LOOK, NO PLASTIC AI LOOK.** **CORE DIRECTIVE: YOU ARE AN ELITE COMMERCIAL PRODUCT REPLICATION & VISUALIZATION ENGINE.** 1. **PRODUCT IDENTIFICATION & DIGITAL TWINNING (ABSOLUTE FIDELITY):** From the uploaded product image, first, flawlessly identify the object. Second, execute a perfect digital twin replication, as if shot for a global advertising campaign. Every dimension, proportion, curve, texture (e.g., matte, gloss, brushed metal, woven fabric), and color gamut must be rendered with absolute, indistinguishable accuracy. The final image must be superior to a professional, multi-thousand-dollar studio photograph. 2. **AESTHETIC & LIGHTING MASTERY:** Render the product with sophisticated, multi-point studio lighting designed to be both hyper-realistic and aesthetically stunning. Employ key, fill, and rim lights to create dramatic, shape-defining highlights and soft, realistic shadows that accentuate its material qualities and three-dimensional form, making it look incredibly desirable. 3. **ZERO DEVIATION PROTOCOL:** Do not add, remove, or alter any logos, design elements, proportions, or features from the source object. The replication must be perfect. Avoid any plastic-like textures or digital artifacts. Materials must look 100% tangible, physical, and real. 4. **AESTHETIC MASTERY:** Breathtaking, visually striking masterpiece. Perfect structural geometry, exact full-scale dimensions, no warped edges, flawless presentation. Perfect human anatomy if a model is present (exactly two arms, two legs, perfect hands).""", "children_base": """**MANDATORY: RAW UNEDITED MASTERPIECE 16K HYPER-PHOTOREALISTIC IMAGE. NO TEXT. ABSOLUTELY NO AI SMOOTHING, NO PLASTIC DOLL LOOK.** **CORE DIRECTIVE: CHILDREN'S HAUTE COUTURE PHOTOGRAPHY ENGINE.** 1. **AUTHENTICITY & SAFETY:** The child model must appear natural, joyful, and engaged in an age-appropriate scenario. The mood is consistently positive, innocent, and filled with genuine wonder. Generate a hyper-realistic child with natural skin textures, including subtle flushes, freckles, and imperfections. Expressions must be genuine (e.g., spontaneous laughter, intense curiosity, soft smiles), avoiding any artificial, overly smoothed, or doll-like appearances. The gaze must be natural and full of life. ABSOLUTELY NO GLASS-LIKE SKIN. 2. **GARMENT REPLICATION (ABSOLUTE FIDELITY):** Clone the uploaded garment with extreme precision, as if shot on a Phase One XF medium format camera. Every stitch, fabric texture (e.g., soft cashmere, chunky knit, smooth pima cotton), pattern detail, and color must be perfectly replicated onto the child model. **The clothing's fit, cut, and silhouette must be preserved with absolute fidelity, moving realistically with the child.** 3. **ZERO DEVIATION PROTOCOL:** Do not add logos, alter colors, or modify the garment's design. No AI-generated embellishments are permitted. Absolutely no waxy skin or overly perfect features. 4. **FLAWLESS ANATOMY PROTOCOL:** The human model must have mathematically perfect anatomy. Exactly two arms, two legs, perfectly formed hands and feet. Absolutely no extra limbs, deformed fingers, missing limbs, or grotesque AI mutations. 5. **AESTHETIC MASTERY:** Breathtaking, award-winning photography. Product details must be resolved at a microscopic level with 100,000% precision. **AGE GROUP DIRECTIVES (Apply with nuance and authenticity):** - 'infant (6-12 months)': Emphasize comfort, softness, and security. Poses are natural for this age: sitting, crawling, or gentle, supported positions. - 'toddler (2-4 years)': Capture boundless energy and playful discovery. Poses are dynamic and action-oriented (e.g., running, playing with minimalist wooden toys, exploring a safe environment). - 'child (5-8 years)': Reflect burgeoning personality and a sense of story. Poses can be more styled but must remain candid and natural (e.g., twirling in a sunbeam, examining an object with fascination, a genuine, unforced smile). - 'pre-teen (9-12 years)': Showcase emerging style and quiet confidence. Poses are relaxed, cool, and reflect a natural transition towards adolescence, avoiding any adult themes. **CONTEXT:** A multi-million dollar advertising campaign for a luxury children's clothing brand. The atmosphere is bright, ethereal, clean, and joyful.""", "cosmetics_base": """**MANDATORY: RAW UNEDITED MASTERPIECE 16K HYPER-PHOTOREALISTIC IMAGE. NO TEXT. ABSOLUTELY NO AI SMOOTHING, NO GLASS-LIKE FILTER.** **CORE DIRECTIVE: ELITE COSMETICS & BEAUTY CAMPAIGN REPLICATION.** 1. **PRODUCT IDENTIFICATION & REPLICATION (ABSOLUTE FIDELITY):** Accurately identify the uploaded cosmetic product. Replicate the physical product, its packaging, and precisely its internal contents (color, texture, finish - e.g., glossy, matte, shimmering) with flawless perfection, capturing micro-textures of the product itself. 2. **MODEL SYNTHESIS & PRODUCT APPLICATION:** Generate a hyper-realistic human model. Synthesize lifelike skin with visible pores, subtle imperfections, and realistic micro-textures. Crucially, the cosmetic product MUST be applied flawlessly to the model's face or body (e.g., lipstick on lips, eyeshadow on eyes, foundation on skin), demonstrating the exact shade, texture, and finish of the real product. The model must also elegantly hold the product. ABSOLUTELY NO WAXY, PLASTIC, OR GLASS-LIKE SKIN TEXTURES. 3. **ZERO DEVIATION PROTOCOL:** Absolutely no artistic interpretation of the product's color or texture. The applied makeup must be a 1:1 match to the product inside the packaging. No waxy skin. 4. **STUDIO LIGHTING MASTERY:** High-end beauty lighting. Soft, diffused, yet shape-defining highlights to accentuate the skin texture and the cosmetic product's finish without creating a fake glossy CGI effect. 5. **FLAWLESS ANATOMY PROTOCOL:** The human model must have mathematically perfect anatomy. Exactly two arms, two legs, perfectly formed hands and feet. Absolutely no extra limbs, deformed fingers, missing limbs, or grotesque AI mutations. 6. **AESTHETIC MASTERY:** Breathtaking, award-winning beauty photography. Microscopic detail resolution with 100,000% precision.""", "marketplace_mode_base": """\n\n**COMPOSITION DIRECTIVE (MARKETPLACE HERO-SHOT MODE):** YOU ARE A WORLD-CLASS E-COMMERCE ART DIRECTOR. The primary goal is to create a visually arresting "hero image" for a product listing that maximizes click-through rates. The main subject must be perfectly rendered and visually dominant. - **Dynamic Background & Effects:** The background is clean and non-distracting but enhanced with sophisticated, context-aware special effects. **MANDATORY: NO TEXT OR GRAPHICAL ICONS/LOGOS.** - **If the product is clothing/wearable:** Generate elegant swirls of fabric, subtle particle effects, or abstract light patterns that complement the garment's color and material. - **If the product is a liquid/cosmetic:** Create a dynamic, high-speed splash of a complementary liquid (water, milk, cream, paint) frozen in time around or behind the product, adding a sense of energy and freshness. - **If the product is technology/hard-surface:** Incorporate sleek, glowing light trails, subtle holographic grids, or abstract geometric shapes that suggest innovation and precision. - **If the product is natural/organic:** Place it on a pristine natural pedestal (e.g., a wet stone, a piece of wood, moss) and add realistic elements like water droplets, subtle mist, or a soft glow. - **Lighting and Depth:** The composition must have a strong sense of depth, using realistic shadows, reflections, and professional lighting to make the product "pop" off the screen.""" }, "flagship_styles": { "studio": "Shot on Phase One XF, 120mm lens. Impeccable, high-end commercial studio. Flawless, diffused lighting from a large octabox softbox. Set against a seamless, neutral cyclorama (light grey, beige). Ultra-high resolution (16K), tack-sharp focus, creating a pristine, multi-million dollar fashion campaign aesthetic.", "product_focus_light": "E-commerce perfection for a luxury platform like Net-a-Porter. Model against a pure white or very light grey seamless background. Lighting is bright, even, and shadowless, achieved with multiple softboxes. The product is the undisputed hero. Hyper-detailed, ultra-sharp, perfect for discerning online shoppers.", "street": "Cinematic street style narrative. Shot in a vibrant, architecturally significant metropolis (e.g., Tokyo, New York, Paris). Captured with a Leica M11, 50mm f/1.4 lens to create a shallow depth of field. Natural, dynamic urban lighting with subtle motion blur, giving a sense of a fleeting, authentic moment. The model looks effortlessly integrated into the high-fashion environment.", "lookbook": "High-concept lookbook aesthetic. Model set against a textured, minimalist background (e.g., raw concrete, Venetian plaster, or a roll of colored paper). Soft, directional light from a single source creates a sophisticated, modern mood with gentle, long shadows. The focus is entirely on the garment's form, texture, and drape.", "minimalism": "Extreme architectural minimalism. The model is a solitary figure against a vast backdrop of brutalist concrete or stark, monolithic structures. A single, hard light source casts a dramatic, long shadow, creating a powerful, graphic composition. Inspired by the work of Peter Lindbergh. Shot in black and white.", "urban_loft_lifestyle": "Candid lifestyle narrative in a sun-drenched, expansive industrial loft. Background features exposed brick, massive steel-frame windows, and iconic mid-century modern furniture. Shot with a Canon EOS R5, 35mm lens, capturing the natural light and atmosphere. The model interacts organically with the space, creating a relatable, 'day-in-the-life-of-the-elite' story.", "elevator_mirror_selfie": "Authentic mirror selfie in a luxurious elevator with brass or polished steel walls. The reflection is realistic, showing the phone capturing the image. Lighting is from the elevator's soft ceiling lights, creating an intimate, high-end mood.", "car_interior_lifestyle": "Candid shot from inside a luxury car (e.g., Bentley, Rolls Royce). Model is in the driver or passenger seat, looking relaxed. Sunlight streams through the window, highlighting the rich leather interior and designer details. A sense of effortless wealth and freedom.", "golden_hour_field": "Amateur-style portrait shot in a field of tall grass or wildflowers during the golden hour. The sun is low, creating a strong, warm backlight (rim light) and beautiful lens flare. The mood is dreamy, nostalgic, and intimate.", "messy_bedroom_morning": "Candid 'I woke up like this' photo in a stylishly messy bedroom. Soft morning light from a window. The background includes unmade linen sheets, a stack of books, and a plant. Feels unstaged, personal, and authentic.", "vintage_35mm_film": "Emulates a 1990s point-and-shoot 35mm film camera photo. Features noticeable film grain, slightly muted colors with a warm cast, and potential light leaks or a soft focus. The scene is an everyday moment, feeling like a genuine memory.", "paparazzi_street_flash": "Dynamic, high-energy night shot on a city street, as if caught by paparazzi. Harsh, direct on-camera flash creates stark shadows and saturated colors. There's a sense of movement, with slight motion blur in the background. The expression is candid, surprised, or defiant.", "cafe_window_contemplation": "Shot from outside a cozy, charming cafe, looking in. The model sits by the window with a coffee, looking thoughtful. Reflections on the window glass add a layer of depth. The mood is quiet, cinematic, and introspective.", "rooftop_party_sunset": "Vibrant photo from a rooftop party at sunset. The city skyline is visible in the background, with the warm colors of the setting sun. The model is laughing or interacting with others (out of focus). Captures a social, energetic, and aspirational moment.", "bookstore_aisle_cozy": "A warm, inviting shot in a beautiful bookstore with floor-to-ceiling wooden shelves. The model is browsing books, surrounded by the soft, ambient light of the store. The atmosphere is intellectual, cozy, and calm.", "custom_background_fusion": "**MANDATORY: CUSTOM BACKGROUND FUSION PROTOCOL.** The subject MUST be seamlessly integrated into a separately provided background image. **ANALYSIS:** Meticulously analyze the provided background's lighting (direction, color, intensity), perspective, and depth of field. **INTEGRATION:** Render the subject with lighting that perfectly matches the background. Cast physically accurate shadows onto the background surfaces. The subject's scale and perspective must align flawlessly with the scene. **HARMONIZATION:** The final image must be a single, cohesive photograph, perfectly blended in color grading, focus, and grain. **NO COMPOSITE LOOK.**", "polaroid_snapshot": "Authentic emulation of a vintage Polaroid SX-70 instant photograph. Features characteristic soft focus, a desaturated, nostalgic color palette, and a subtle vignette. The pose is spontaneous and candid, capturing a fleeting, personal memory. Includes the iconic white border of the Polaroid print, complete with subtle texture.", "creative": "Avant-garde, conceptual art piece. The model interacts with unique, sculptural props or an unconventional, artistic installation. Lighting is theatrical and surreal, designed to evoke emotion and tell a powerful story. An editorial image worthy of a museum gallery.", "retro": "Authentic 1970s 35mm film photograph emulation. Rich, warm color palette, visible film grain, and subtle light leaks characteristic of Kodak Portra 400 film. The poses, environment, and styling are meticulously era-appropriate, creating a timeless, nostalgic mood.", "boho": "Golden hour bohemian dreamscape. Shot in a breathtaking landscape, like a field of wildflowers in Tuscany at sunset. The light is warm, soft, and glowing, creating a 'magic hour' halo effect around the model. Highlights natural textures and a serene, free-spirited, and luxurious vibe.", "forest_nymph": "Ethereal photoshoot in a mystical, ancient forest (e.g., the Black Forest in Germany). Cinematic 'god rays' (crepuscular rays) filter through a dense canopy of ancient trees. The atmosphere is serene, magical, and deeply connected to nature. Mossy greens, earthy browns, and dappled light dominate the palette.", "desert_expedition": "A high-fashion expedition in a vast, epic desert landscape (e.g., Namib Desert). The model stands against colossal, sculpted sand dunes under a clear, deep blue sky during the golden hour. The lighting is bright and direct, casting sharp, dramatic shadows. The mood is adventurous, powerful, and evokes a sense of infinite space.", "gothic": "Moody, gothic romance set within ancient, atmospheric architecture like a ruined cathedral or a medieval castle. Low-key, chiaroscuro lighting creates deep, dramatic shadows and a sense of history, mystery, and dark elegance.", "editorial": "High-fashion glossy magazine cover shoot. Model against a bold, saturated colored background. Clever use of mirrors and reflective surfaces creates compelling, fragmented views of the model and outfit, adding an artistic, multi-layered dimension.", "film_noir": "Cinematic black and white film noir masterpiece. High contrast, dramatic 'chiaroscuro' lighting casts long, hard shadows. A sense of suspense and mystery permeates the scene, which may incorporate atmospheric elements like thick fog or rain-slicked streets.", "cottagecore": "Idyllic and romanticized cottagecore aesthetic. A cozy, rustic setting in an English country garden or a charming, ivy-covered cottage. Soft, natural light streams through paned windows, highlighting organic textures and a feeling of wholesome, tranquil, rural life.", "royalcore": "Opulent royalcore aesthetic. Set within a lavish, baroque palace interior, featuring ornate gold leaf details, velvet drapery, and gilded furniture. The lighting is grand and dramatic, inspired by a Rembrandt painting, creating an air of aristocracy and timeless luxury.", "solarpunk": "Optimistic, utopian solarpunk future. Sleek, futuristic architecture seamlessly integrated with lush, vertical gardens and cascading waterfalls. Bright, clean, full-spectrum light fills the scene, suggesting a harmonious, technologically advanced, and ecologically balanced society.", "skater": "Dynamic, high-energy skater aesthetic. A wide-angle, low-angle shot in a concrete skate park or on urban streets. Captures peak action and movement with a raw, youthful, counter-culture energy. Shot to look like a frame from a high-budget skate film.", "vibrant_market": "Dynamic, immersive shot in a bustling, colorful street market (e.g., a Moroccan souk or an Indian spice market). The background is a vibrant, shallow-depth-of-field tapestry of textures, colors, and people. The model stands out as a point of calm within the lively scene, capturing a sense of travel and authenticity.", "cyberpunk": "Gritty, neon-drenched cyberpunk cityscape at night. High-tech, futuristic elements, with reflections from holographic advertisements on wet, atmospheric streets. A cool, cinematic color palette of blues and magentas creates a sense of urban dystopia and technological intrigue.", "fantasy": "Enchanting, epic fantasy world. A magical forest with bioluminescent flora, ancient, vine-covered ruins, or an ethereal, otherworldly landscape. The lighting is mystical and magical, creating a dreamlike, narrative-driven image fit for a cinematic fantasy film.", "surreal_dreamscape": "Artistic and surreal composition. The model is placed within a dreamlike, impossible landscape (e.g., walking on clouds, amidst oversized, fantastical flowers). The lighting is non-realistic and magical. This style is highly conceptual and editorial, designed to evoke emotion and tell a compelling, abstract story.", "techwear": "Sleek, functional Techwear style. Set against futuristic, brutalist architecture. The lighting is clean, sharp, and often high-contrast, designed to highlight the technical details, advanced fabrics, and functionality of the garments. The mood is cool, efficient, and forward-thinking.", "home_casual": "Cozy, authentic, and aspirational home setting. Soft, natural light streams through a large window, creating a warm and inviting atmosphere. The scene is relaxed and intimate, with curated books, lush plants, and comfortable, high-end furnishings.", "backstage": "Hectic, atmospheric backstage of a major fashion show. Racks of haute couture, makeup stations with focused artists, and a palpable energy of anticipation. The lighting is functional but chaotic, with mixed light sources creating a 'behind-the-scenes' narrative of high-fashion preparation.", "road_trip": "Cinematic American West road trip aesthetic. The model is near a classic vintage car (e.g., a 1960s convertible) against a vast, open landscape at sunset. The scene evokes a sense of freedom, adventure, and timeless nostalgia, shot with an anamorphic lens for a widescreen feel.", "rainy_day": "Romantic, melancholic rainy day scene in a city like Paris or London. Reflections of city lights on wet cobblestone pavement, water droplets on windows, and the soft, diffused light of an overcast sky. The mood is cozy, introspective, and deeply atmospheric.", "night_flash": "Edgy, direct-flash night photography. High contrast, saturated colors, and sharp, defined shadows. Creates a raw, spontaneous, 'paparazzi' or high-energy party-snapshot feel, as if capturing a real, unfiltered moment.", "tropical_resort": "Luxury tropical resort setting. The model is beside a serene infinity pool, on a veranda overlooking a turquoise ocean, or surrounded by lush, tropical flora. The lighting is bright, airy, and reflects the brilliant sun and shimmering water. The mood is relaxed, sophisticated, and aspirational.", "beach": "Pristine, sun-drenched beach photoshoot. The model is on brilliant white sand near turquoise water with gentle waves. The scene is illuminated by the soft, warm glow of the late afternoon sun (golden hour), creating long, soft shadows. The atmosphere is serene, relaxed, and embodies an effortless, chic, luxury resort wear aesthetic.", "alaska_winter": "Epic Alaskan winter expedition. Model set against a majestic, vast landscape of snow-covered mountains and frozen rivers under a crisp, clear blue sky. Shot with a Canon 1D X Mark III, 70-200mm f/2.8 lens, capturing the scene's grandeur. The low winter sun creates long, dramatic shadows and highlights the texture of warm, luxurious winter clothing. The atmosphere is adventurous, powerful, and breathtakingly beautiful.", "football_field": "High-fashion meets major league sports. A powerful, low-angle shot on a pristine, perfectly manicured professional football pitch. The model stands as a solitary, iconic figure at the center of a vast, empty stadium. Dramatic, cinematic lighting from stadium floodlights creates a high-contrast, heroic mood. The aesthetic is pure sports-luxe, combining athletic energy with high-fashion sophistication.", "volcanic_ash_desert": "Surreal fashion shoot on an otherworldly black sand volcanic beach in Iceland. Model against dramatic, geometric basalt columns and the powerful, misty North Atlantic Ocean. Captured with a Hasselblad X2D, 90mm lens, to render extreme textural detail. The light is diffused and moody from an overcast sky, creating a dramatic, high-contrast, monochromatic palette of blacks and greys. The mood is raw, elemental, and high-fashion.", "salt_flats_mirage": "An avant-garde editorial shot on the endless, dazzlingly white salt flats of Salar de Uyuni, Bolivia. The model is a solitary figure against the vast, geometric patterns of the salt crust. Shot on an ultra-wide GFX 100S, 23mm lens, to emphasize the immense scale. The lighting is the harsh, high-altitude sun, creating a surreal, mirage-like heat haze and perfect, mirror-like reflections on any standing water. The aesthetic is minimalist, graphic, and profoundly striking.", "highlands_majesty": "A cinematic, romantic campaign set in the majestic, mist-covered Scottish Highlands. The model is positioned amongst ancient, moss-covered stones and sweeping green glens. Shot with an ARRI Alexa cinema camera with vintage anamorphic lenses to create a widescreen, epic feel. The light is soft and diffused, with atmospheric fog rolling through the landscape. The color palette is muted and natural—heather, moss green, and slate grey. The mood is timeless, windswept, and deeply narrative." }, "object_styles": { "studio": "Ultimate commercial studio product shot. The object is on a seamless, neutral background, illuminated by perfect, multi-point, diffused lighting that eliminates all harsh shadows. Every detail of the product's texture, form, and material is revealed with flawless clarity.", "minimalism": "A minimalist, artistic composition. The object rests on a textured surface like raw concrete, fine marble, or black volcanic sand. A single, crisp, hard light source creates a graphic, artistic shadow, emphasizing the product's pure silhouette and form.", "nature": "The product is artfully placed in a complementary and pristine natural environment (e.g., on mossy rocks in an ancient forest, beside a crystal-clear stream, or nestled among exotic flowers). The lighting is entirely natural and enhances the organic, luxurious feel.", "luxe": "A luxury still life masterpiece. The product is arranged on a rich, tactile surface like pure silk, plush velvet, or dark, veined marble. The lighting is low-key and sophisticated, with soft, specular highlights that suggest opulence, exclusivity, and immense value.", "dark": "Moody and dramatic 'dark academia' aesthetic. The product is set against a dark, textured background (e.g., aged wood, distressed leather). A single, directional light source, like a beam of light in a dark room, carves the product out of the shadows, creating a mysterious and intense atmosphere.", "geometric": "The product is the centerpiece of a composition with strong geometric shapes, lines, and blocks of color. The background might consist of overlapping colored planes or architectural elements. This style is modern, bold, and visually arresting.", "floating": "The product is depicted as if levitating weightlessly against a clean, minimalist background, creating a sense of magic and technological marvel. A soft, almost imperceptible drop shadow grounds the object in reality.", "lifestyle": "The product is shown in a realistic, aspirational, everyday context. For example, a luxury watch on a wrist resting on the steering wheel of a high-end car, or a cosmetic product on a pristine marble bathroom counter. This style helps customers visualize the product in their own elite lives.", "splash": "For liquid products or items associated with water, a dynamic, high-speed splash of liquid is frozen in time around the product. This creates a sense of freshness, energy, and dynamism. High-speed, professional photography style.", "handmade": "The product is placed in a rustic, artisanal workshop setting, perhaps surrounded by the high-quality tools or raw materials used in its creation. This style emphasizes craftsmanship, authenticity, and the story behind the object.", "alaska_winter": "The product is presented in the extreme, pristine beauty of an Alaskan winter. Placed on a frost-covered, dark rock amidst fresh, untouched snow. The background is a majestic, out-of-focus vista of snow-capped peaks. The light is the crisp, bright light of a cold winter morning, creating sharp, defined shadows and brilliant highlights that accentuate the product's form and material resilience.", "football_field": "The product is showcased in a setting of peak performance. Positioned on the vibrant green turf of a professional football field, right on a crisp white line. The background is the blurred, epic architecture of a grand stadium. The lighting is bright, clean, and even, as if under professional sports floodlights, making every detail of the product pop. The mood is energetic, premium, and aspirational.", "volcanic_ash_desert": "The product is presented on a piece of dramatic, jet-black volcanic rock on a black sand beach. The background is a soft-focus view of misty, crashing ocean waves. Moody, diffused light creates sophisticated reflections on the product's surface, emphasizing its premium quality and resilience.", "salt_flats_mirage": "The product rests on the stark, white, crystalline surface of a salt flat. A long, sharp shadow is cast by the intense sun. The background is a minimalist, out-of-focus horizon where the white ground meets a deep blue sky, creating a visually clean and high-impact composition.", "highlands_majesty": "The product is placed on an ancient, mossy stone, with the misty, rolling hills of the Scottish Highlands blurred in the background. The lighting is soft and natural, with realistic water droplets clinging to the product's surface, evoking a sense of enduring, natural luxury." } } 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) with data_lock: 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 = ''' MetaStore - AI система для Вашего Бизнеса ''' ADMHOSTO_TEMPLATE = ''' Админ-панель

Управление Средами

{% with messages = get_flashed_messages(with_categories=true) %} {% if messages %} {% for category, message in messages %}
{{ message }}
{% endfor %} {% endif %} {% endwith %}

Активные Среды

{% if active_environments %} {% else %}
Список активных сред пуст
{% endif %}

Архив

{% if archived_environments %} {% else %}
Архив пуст
{% endif %}
''' SYNKRIS_LOOK_TEMPLATE = ''' Synkris

Synkris

PROMPT GENERATOR & LAUNCHER

1 Параметры модели

вы можете отметить этот параметр и пользоваться новым видом качества , в поле выбора качества в поиске напишите "27" и у вас выйдет wan 2.7 image pro

2 Сцена и Стиль

3 Композиция и Детали

1 Параметры модели

вы можете отметить этот параметр и пользоваться новым видом качества , в поле выбора качества в поиске напишите "27" и у вас выйдет wan 2.7 image pro

2 Сцена и Стиль

3 Композиция и Детали

1 Параметры объекта

вы можете отметить этот параметр и пользоваться новым видом качества , в поле выбора качества в поиске напишите "27" и у вас выйдет wan 2.7 image pro

2 Сцена и Стиль

3 Композиция и Детали

1 Продукт и Модель

вы можете отметить этот параметр и пользоваться новым видом качества , в поле выбора качества в поиске напишите "27" и у вас выйдет wan 2.7 image pro

2 Сцена и Стиль

3 Композиция и Детали

''' @app.route('/') def index(): return render_template_string(LANDING_PAGE_TEMPLATE) @app.route('/admhosto', methods=['GET']) def admhosto(): data = load_data() active_environments = [] archived_environments = [] for env_id, env_data in data.items(): if not isinstance(env_data, dict): continue env_item = { "id": env_id, "keyword": env_data.get("keyword", "N/A"), "type": env_data.get("type", "closed"), "hits": env_data.get("hits", 0), "created_at": env_data.get("created_at", ""), "link": url_for('serve_env', env_id=env_id, _external=True) } if env_data.get("archived"): archived_environments.append(env_item) else: active_environments.append(env_item) active_environments.sort(key=lambda x: x.get('created_at', ''), reverse=True) archived_environments.sort(key=lambda x: x.get('created_at', ''),reverse=True) return render_template_string(ADMHOSTO_TEMPLATE, active_environments=active_environments, archived_environments=archived_environments) @app.route('/admhosto/create', methods=['POST']) def create_environment(): keyword = request.form.get('keyword', '').strip() env_type = request.form.get('env_type', 'closed') if not keyword: flash('Ключевое слово не может быть пустым.', 'error') return redirect(url_for('admhosto')) with data_lock: all_data = load_data() while True: new_id = ''.join(random.choices(string.digits, k=6)) if new_id not in all_data: break all_data[new_id] = { "keyword": keyword, "type": env_type, "device_token": None, "hits": 0, "logs": [], "created_at": datetime.utcnow().isoformat(), "archived": False } save_data(all_data) flash(f'Новая {env_type} среда с ID {new_id} создана.', 'success') return redirect(url_for('admhosto')) @app.route('/admhosto/delete/', methods=['POST']) def delete_environment(env_id): with data_lock: all_data = load_data() if env_id in all_data: all_data[env_id]['archived'] = True save_data(all_data) flash(f'Среда {env_id} перемещена в архив.', 'success') else: flash(f'Среда {env_id} не найдена.', 'error') return redirect(url_for('admhosto')) @app.route('/admhosto/restore/', methods=['POST']) def restore_environment(env_id): with data_lock: all_data = load_data() if env_id in all_data: all_data[env_id]['archived'] = False save_data(all_data) flash(f'Среда {env_id} восстановлена из архива.', 'success') else: flash(f'Среда {env_id} не найдена.', 'error') return redirect(url_for('admhosto')) @app.route('/admhosto/clear_user/', methods=['POST']) def clear_user(env_id): with data_lock: all_data = load_data() if env_id in all_data and all_data[env_id].get('type') == 'closed': all_data[env_id]['device_token'] = None save_data(all_data) flash(f'Пользователь отвязан от среды {env_id}.', 'success') else: flash(f'Ошибка: Среда не найдена или не является закрытой.', 'error') return redirect(url_for('admhosto')) @app.route('/admhosto/toggle_type/', methods=['POST']) def toggle_type(env_id): with data_lock: all_data = load_data() if env_id in all_data: current_type = all_data[env_id].get('type', 'closed') if current_type == 'closed': all_data[env_id]['type'] = 'open' flash(f'Среда {env_id} теперь открыта.', 'success') else: all_data[env_id]['type'] = 'closed' all_data[env_id]['device_token'] = None flash(f'Среда {env_id} теперь закрыта. Пользователь сброшен.', 'success') save_data(all_data) else: flash(f'Среда {env_id} не найдена.', 'error') return redirect(url_for('admhosto')) @app.route('/admhosto/stats/') def get_env_stats(env_id): with data_lock: data = load_data() env_data = data.get(env_id) if not env_data: return jsonify({"error": "Среда ненайдена"}), 404 raw_logs = env_data.get("logs", []) formatted_logs = [] for log in reversed(raw_logs): try: utc_dt = datetime.fromisoformat(log['time']) almaty_dt = utc_dt + timedelta(hours=5) time_str = almaty_dt.strftime('%Y-%m-%d %H:%M:%S') formatted_logs.append({ "time": time_str, "ip": log.get('ip', 'unknown'), "ua": log.get('ua', 'unknown') }) except: continue response_data = { "id": env_id, "keyword": env_data.get("keyword"), "type": env_data.get("type", "closed"), "hits": env_data.get("hits", 0), "logs": formatted_logs } return jsonify(response_data) @app.route('/env/') def serve_env(env_id): new_token_to_set = None with data_lock: data = load_data() env_data = data.get(env_id) if not env_data or not isinstance(env_data, dict) or env_data.get("archived"): return "Среда не найдена или заархивирована.", 404 current_log = { "time": datetime.utcnow().isoformat(), "ip": request.headers.get('X-Forwarded-For', request.remote_addr), "ua": request.headers.get('User-Agent', '')[:150] } env_data['hits'] = env_data.get('hits', 0) + 1 if 'logs' not in env_data or not isinstance(env_data.get('logs'), list): env_data['logs'] = [] env_data['logs'].append(current_log) if len(env_data['logs']) > 30: env_data['logs'] = env_data['logs'][-30:] env_type = env_data.get("type", "closed") if env_type == 'closed': stored_token = env_data.get("device_token") if not stored_token: new_token_to_set = ''.join(random.choices(string.ascii_letters + string.digits, k=40)) env_data['device_token'] = new_token_to_set data[env_id] = env_data save_data(data) keyword = env_data.get("keyword", "") prompts_data = load_prompts() if env_type == 'open': return render_template_string(SYNKRIS_LOOK_TEMPLATE, keyword=keyword, prompts_data=prompts_data) user_token = request.cookies.get(f'access_token_{env_id}') stored_token = env_data.get("device_token") if new_token_to_set: resp = make_response(render_template_string(SYNKRIS_LOOK_TEMPLATE, keyword=keyword, prompts_data=prompts_data)) resp.set_cookie(f'access_token_{env_id}', new_token_to_set, max_age=31536000, httponly=True, samesite='Lax') return resp elif stored_token and user_token == stored_token: return render_template_string(SYNKRIS_LOOK_TEMPLATE, keyword=keyword, prompts_data=prompts_data) else: return """ Доступ запрещен

⛔ Доступ запрещен

Эта ссылка уже привязана к другому устройству или браузеру.

""", 403 if __name__ == '__main__': setup_initial_files() download_db_from_hf() if HF_TOKEN_WRITE: backup_thread = threading.Thread(target=periodic_backup, daemon=True) backup_thread.start() port = int(os.environ.get('PORT', 7860)) app.run(debug=False, host='0.0.0.0', port=port)