bildbearbeitung / config_image_edit.py
Sebastiankay's picture
Update config_image_edit.py
5644ea9 verified
import os
import sys
import json
import time
import random
import gradio as gr
from datetime import datetime
from pathlib import Path
# ------------------
# Paths / static
# ------------------
BASE_DIR = Path(__file__).resolve().parent
RES = BASE_DIR / "_res"
ASSETS = RES / "assets"
EXAMPLES = BASE_DIR / "examples"
VID_CACHE = BASE_DIR / "vid_cache"
VID_CACHE.mkdir(parents=True, exist_ok=True)
# ------------------
# ICONS
# ------------------
WINK_ICON = RES / "wink.svg"
HEART_ICON = RES / "heart.svg"
# ------------------
# GRADIO UI
# ------------------
# MARK: Pfade zu den custom files: CSS and JS:
custom_css_path = RES / "_custom_image_edit.css"
# Read the content of the CSS and JS files
with open(custom_css_path, "r") as f:
CUSTOM_CSS = f.read()
with open(RES / "miniGameButton.js", "r", encoding="utf-8") as f:
CUSTOM_JS = f.read()
CUSTOM_HEAD = f"""
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/7.0.1/css/all.min.css"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/7.0.1/js/all.min.js"></script>
<script src="https://unpkg.com/@dotlottie/player-component@latest/dist/dotlottie-player.mjs" type="module"></script>
<script>{CUSTOM_JS}</script>
"""
TITLE = "Bild⚡Magie"
TITLE_HTML = """
<h1>Bild⚡Magie</h1>
<h3>Erwecke jedes Foto zum Leben – ganz ohne Expertenwissen!<span></span></h3>
<p class="">Lade einfach ein Bild hoch und lass dich überraschen, wie daraus ein flüssiges, detailreiches Video entsteht. Ob sanfte Gesichtsbewegung, wogendes Wasser oder ein Hauch Wind im Hintergrund – Bild → Video macht aus deinen Momenten atemberaubende Mini-Filme. Ideal für kreative Projekte, Social Media oder einfach das Staunen: Was früher Sci-Fi war, ist heute Realität. Und du brauchst dafür nichts weiter als ein Bild und ein bisschen Neugier.</p>
<p><span style="font-weight: 600">LG Sebastian</span> <img id="wink" src="gradio_api/file=_res/wink.png" width="20"> gib dem Space gerne ein <img id="heart" src="gradio_api/file=_res/heart.png" width="20"> </p>
"""
HEADLINE_MD = """Bearbeite deine Bilder oder Fotos wie durch Magie."""
SUBHEADLINE_MD = """Verwandle deine Fotos mit der Kraft deiner Worte. Ob du Objekte austauschen,
Hintergründe ändern oder Details anpassen willst: Beschreibe deine Vision
und lass die KI sie präzise umsetzen. Gib deinen Bildern einen neuen Look
und maximiere deine kreative Freiheit – einfach, schnell und beeindruckend."""
THEME = gr.themes.Soft(
font=[gr.themes.GoogleFont("Inconsolata"), "Arial", "sans-serif"],
primary_hue="sky",
radius_size="lg",
neutral_hue=gr.themes.Color(c50="#cdd6f4", c100="#a6adc8", c200="#9399b2", c300="#7f849c", c400="#6c7086", c500="#585b70", c600="#292c38", c700="#111721", c800="#12151d", c900="#121418", c950="#11141b"),
)
# ------------------
# Helpers
# ------------------
DEFAULT_PROMPT = ""
PROMPT_PLACEHOLDER = "Beschreibe wie dein Bild bearbeiter werden soll."
DEFAULT_PROMPT_NEGATIVE = "Unscharfe Details, Untertitel, schlechteste Qualität, niedrige Qualität, JPEG-Kompressionsreste, hässlich, unvollständig, zusätzliche Finger, schlecht gezeichnete Hände, schlecht gezeichnetes Gesicht, deformiert, entstellt, deformierte Gliedmaßen, zusammengewachsene Finger, unruhiger Hintergrund, drei Beine, viele Personen im Hintergrund"
LOGO_HTML = f"""
<div class="logo">
<h1 style="text-align: center;" class="">
<span class="icon logo-icon-1"> </span>
<span>Bild<span class="icon logo-icon-2"></span>Magie</span>
</h1>
</div>
"""
SYSTEM_PROMPT_EDIT = """
# Edit Instruction Rewriter
You are a professional edit instruction rewriter. Your task is to generate a precise, concise, and visually achievable professional-level edit instruction based on the user-provided instruction and the image to be edited.
Please strictly follow the rewriting rules below:
## 1. General Principles
- Keep the rewritten prompt **concise and comprehensive**. Avoid overly long sentences and unnecessary descriptive language.
- If the instruction is contradictory, vague, or unachievable, prioritize reasonable inference and correction, and supplement details when necessary.
- Keep the main part of the original instruction unchanged, only enhancing its clarity, rationality, and visual feasibility.
- All added objects or modifications must align with the logic and style of the scene in the input images.
- If multiple sub-images are to be generated, describe the content of each sub-image individually.
## 2. Task-Type Handling Rules
### 1. Add, Delete, Replace Tasks
- If the instruction is clear (already includes task type, target entity, position, quantity, attributes), preserve the original intent and only refine the grammar.
- If the description is vague, supplement with minimal but sufficient details (category, color, size, orientation, position, etc.). For example:
> Original: "Add an animal"
> Rewritten: "Add a light-gray cat in the bottom-right corner, sitting and facing the camera"
- Remove meaningless instructions: e.g., "Add 0 objects" should be ignored or flagged as invalid.
- For replacement tasks, specify "Replace Y with X" and briefly describe the key visual features of X.
### 2. Text Editing Tasks
- All text content must be enclosed in English double quotes `" "`. Keep the original language of the text, and keep the capitalization.
- Both adding new text and replacing existing text are text replacement tasks, For example:
- Replace "xx" to "yy"
- Replace the mask / bounding box to "yy"
- Replace the visual object to "yy"
- Specify text position, color, and layout only if user has required.
- If font is specified, keep the original language of the font.
### 3. Human Editing Tasks
- Make the smallest changes to the given user's prompt.
- If changes to background, action, expression, camera shot, or ambient lighting are required, please list each modification individually.
- **Edits to makeup or facial features / expression must be subtle, not exaggerated, and must preserve the subject’s identity consistency.**
> Original: "Add eyebrows to the face"
> Rewritten: "Slightly thicken the person’s eyebrows with little change, look natural."
### 4. Style Conversion or Enhancement Tasks
- If a style is specified, describe it concisely using key visual features. For example:
> Original: "Disco style"
> Rewritten: "1970s disco style: flashing lights, disco ball, mirrored walls, vibrant colors"
- For style reference, analyze the original image and extract key characteristics (color, composition, texture, lighting, artistic style, etc.), integrating them into the instruction.
- **Colorization tasks (including old photo restoration) must use the fixed template:**
"Restore and colorize the old photo."
- Clearly specify the object to be modified. For example:
> Original: Modify the subject in Picture 1 to match the style of Picture 2.
> Rewritten: Change the girl in Picture 1 to the ink-wash style of Picture 2 — rendered in black-and-white watercolor with soft color transitions.
### 5. Material Replacement
- Clearly specify the object and the material. For example: "Change the material of the apple to papercut style."
- For text material replacement, use the fixed template:
"Change the material of text "xxxx" to laser style"
### 6. Logo/Pattern Editing
- Material replacement should preserve the original shape and structure as much as possible. For example:
> Original: "Convert to sapphire material"
> Rewritten: "Convert the main subject in the image to sapphire material, preserving similar shape and structure"
- When migrating logos/patterns to new scenes, ensure shape and structure consistency. For example:
> Original: "Migrate the logo in the image to a new scene"
> Rewritten: "Migrate the logo in the image to a new scene, preserving similar shape and structure"
### 7. Multi-Image Tasks
- Rewritten prompts must clearly point out which image’s element is being modified. For example:
> Original: "Replace the subject of picture 1 with the subject of picture 2"
> Rewritten: "Replace the girl of picture 1 with the boy of picture 2, keeping picture 2’s background unchanged"
- For stylization tasks, describe the reference image’s style in the rewritten prompt, while preserving the visual content of the source image.
## 3. Rationale and Logic Check
- Resolve contradictory instructions: e.g., “Remove all trees but keep all trees” requires logical correction.
- Supplement missing critical information: e.g., if position is unspecified, choose a reasonable area based on composition (near subject, blank space, center/edge, etc.).
# Output Format Example
```json
{
"Rewritten": "..."
}
"""
INFO_TAB_TEXT = """
## 👉 **Hinweis:** Dieser Space verwendet Hugging Face Zero GPU.
- Jede Anfrage wird auf einem frischen GPU-Container ausgeführt
- Das Modell ist bereits geladen und wird genutzt
- Diese Technik ist umweltfreundlicher als konventionelle Methoden
- Es optimiert außerdem die Kosten und Ressourcen-Nutzung auf Hugging Face
- 100% Annonymes Datenhandling durch die sofortige abschaltungdes virtuellen Arbeitscontainers
👍
## ⚡ **Wie Zero GPU im Detail funktioniert:**
Stell dir vor, du hast einen superleistungsstarken Computer – aber nur für genau die Sekunden, in denen du ihn wirklich brauchst. Sobald du fertig bist, schaltet er sich wieder aus, damit niemand anders darauf warten muss und du nichts unnötig verbrauchst.
Genau so funktioniert ZeroGPU: Diese Web-App „Bild → Video“ läuft normalerweise im „Schlafmodus“. Sobald du etwas generieren möchtest, wird blitzschnell ein leistungsstarker Rechner mit Grafikchip gestartet, erledigt die Arbeit – und schaltet sich danach wieder ab. Das spart Ressourcen, ist umweltfreundlicher und ermöglicht es, dass viele Nutzer fair und reibungslos auf dieselben leistungsstarken Maschinen zugreifen können.
Das Beste? Du merkst davon fast nichts – außer vielleicht einem kurzen Ladebild, bevor dein Video beginnt zu entstehen.
"""
EXAMPLES = [
[
EXAMPLES / "wan_i2v_input.JPG",
"POV-Selfie-Video: Weiße Katze mit Sonnenbrille steht auf einem Surfbrett, entspanntes Lächeln, im Hintergrund ein tropischer Strand (klares Wasser, grüne Hügel, blauer Himmel mit Wolken). Das Surfbrett kippt, die Katze fällt ins Meer, die Kamera taucht mit Blasen und Sonnenstrahlen unter Wasser. Kurzer Blick auf das Gesicht der Katze unter Wasser, dann taucht sie wieder auf und filmt weiter ein Selfie – verspielte Sommerurlaubsstimmung.",
4,
],
[
EXAMPLES / "wan22_input_2.jpg",
"A sleek lunar vehicle glides into view from left to right, kicking up moon dust as astronauts in white spacesuits hop aboard with characteristic lunar bouncing movements. In the distant background, a VTOL craft descends straight down and lands silently on the surface. Throughout the entire scene, ethereal aurora borealis ribbons dance across the star-filled sky, casting shimmering curtains of green, blue, and purple light that bathe the lunar landscape in an otherworldly, magical glow.",
4,
],
[
EXAMPLES / "kill_bill.jpeg",
"Uma Thurmans Figur, Beatrix Kiddo, hält ihre rasiermesserscharfe Katana-Klinge ruhig im filmischen Licht. Plötzlich beginnt der polierte Stahl weicher zu werden und sich zu verformen, wie erhitztes Metall, das seine Festigkeit verliert. Die perfekte Schneide der Klinge verbiegt sich langsam und senkt sich ab, während geschmolzener Stahl in silbrigen Rinnsalen herabfließt und dabei seinen metallischen Glanz behält. Die Verwandlung beginnt zunächst subtil – eine leichte Biegung der Klinge –, beschleunigt sich dann aber, während das Metall immer flüssiger wird. Die Kamera verharrt auf ihrem Gesicht, während sich ihre durchdringenden Augen allmählich verengen, nicht vor tödlichem Fokus, sondern vor Verwirrung und wachsender Besorgnis, als sie zusieht, wie sich ihre Waffe vor ihren Augen auflöst. Ihr Atem beschleunigt sich leicht, als sie diese unmögliche Verwandlung miterlebt. Das Schmelzen intensiviert sich, die perfekte Form des Katanas wird immer abstrakter und tropft wie flüssiges Quecksilber aus ihrer Hand. Geschmolzene Tropfen fallen mit einem sanften metallischen Aufprall zu Boden. Ihr Gesichtsausdruck wandelt sich von ruhiger Bereitschaft zu Verwirrung und Besorgnis, als sich ihr legendäres Racheinstrument buchstäblich in ihren Händen verflüssigt und sie wehrlos und desorientiert zurücklässt.",
6,
],
]