Spaces:
Running
on
Zero
Running
on
Zero
Commit
·
9de66b7
1
Parent(s):
8f04895
Add Korean localized Qwen Image Editor with LFS
Browse files- .gitattributes +2 -0
- CLAUDE.md +43 -0
- README.md +53 -3
- app.py +320 -0
- cat_sitting.jpg +3 -0
- logo.png +3 -0
- neon_sign.png +3 -0
- pie.png +3 -0
- requirements.txt +9 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
*.jpg filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
*.png filter=lfs diff=lfs merge=lfs -text
|
CLAUDE.md
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# CLAUDE.md
|
| 2 |
+
|
| 3 |
+
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
| 4 |
+
|
| 5 |
+
## Architecture Overview
|
| 6 |
+
|
| 7 |
+
This is a Hugging Face Spaces application that provides image editing capabilities using the Qwen-Image-Edit model. The application consists of a single Gradio interface (`app.py`) that orchestrates:
|
| 8 |
+
|
| 9 |
+
1. **Image Processing Pipeline**: Uses `QwenImageEditPipeline` from diffusers for the core image editing functionality
|
| 10 |
+
2. **Prompt Enhancement**: Integrates with DashScope API (`qwen-vl-max-latest`) to automatically rewrite and enhance user edit instructions using a detailed system prompt
|
| 11 |
+
3. **Gradio Interface**: Web UI with image upload, text input, and advanced parameter controls
|
| 12 |
+
|
| 13 |
+
## Key Components
|
| 14 |
+
|
| 15 |
+
- **Main Pipeline**: `QwenImageEditPipeline` loaded from "Qwen/Qwen-Image-Edit" model
|
| 16 |
+
- **Prompt Polishing**: `polish_prompt()` function that uses DashScope API to enhance user instructions via a comprehensive system prompt template
|
| 17 |
+
- **Inference Function**: `infer()` decorated with `@spaces.GPU(duration=120)` for GPU acceleration
|
| 18 |
+
- **UI Layout**: Single-page Gradio interface with examples and advanced settings accordion
|
| 19 |
+
|
| 20 |
+
## Environment Requirements
|
| 21 |
+
|
| 22 |
+
- **GPU**: CUDA-enabled environment preferred (falls back to CPU)
|
| 23 |
+
- **API Key**: `DASH_API_KEY` environment variable required for prompt enhancement via DashScope
|
| 24 |
+
- **Dependencies**: PyTorch, diffusers (git version), transformers, dashscope, gradio
|
| 25 |
+
|
| 26 |
+
## Development Commands
|
| 27 |
+
|
| 28 |
+
Install dependencies:
|
| 29 |
+
```bash
|
| 30 |
+
pip install -r requirements.txt
|
| 31 |
+
```
|
| 32 |
+
|
| 33 |
+
Run the application:
|
| 34 |
+
```bash
|
| 35 |
+
python app.py
|
| 36 |
+
```
|
| 37 |
+
|
| 38 |
+
## Configuration Notes
|
| 39 |
+
|
| 40 |
+
- Default inference settings: 50 steps, guidance scale 4.0, bfloat16 dtype
|
| 41 |
+
- Hardcoded negative prompt: single space character
|
| 42 |
+
- GPU duration limit: 120 seconds for Spaces environment
|
| 43 |
+
- Examples include three preset image/prompt combinations for testing
|
README.md
CHANGED
|
@@ -1,12 +1,62 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
colorTo: green
|
| 6 |
sdk: gradio
|
| 7 |
sdk_version: 5.43.1
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
---
|
| 11 |
|
| 12 |
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: 퀀 이미지 편집기
|
| 3 |
+
emoji: ✒️
|
| 4 |
+
colorFrom: pink
|
| 5 |
colorTo: green
|
| 6 |
sdk: gradio
|
| 7 |
sdk_version: 5.43.1
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
| 10 |
+
license: apache-2.0
|
| 11 |
+
python_version: 3.11
|
| 12 |
+
---
|
| 13 |
+
|
| 14 |
+
# 퀀 이미지 편집기 (Qwen Image Editor)
|
| 15 |
+
|
| 16 |
+
이 앱은 Qwen-Image-Edit 모델을 사용한 한국어 이미지 편집기입니다.
|
| 17 |
+
|
| 18 |
+
## 한국어 로컬라이제이션 변경사항
|
| 19 |
+
|
| 20 |
+
이 프로젝트는 완전히 한국어로 로컬라이제이션되었습니다:
|
| 21 |
+
|
| 22 |
+
### UI 컴포넌트
|
| 23 |
+
- **제목**: "퀀 이미지 편집기" (로고 + 텍스트)
|
| 24 |
+
- **이미지 업로드 영역**: "이미지를 여기로 끌어다 놓으세요 - 또는 - 업로드하려면 클릭하세요"
|
| 25 |
+
- **프롬프트 입력**: "편집 지시사항을 설명해주세요" (플레이스홀더)
|
| 26 |
+
- **버튼**: "편집!" (실행 버튼)
|
| 27 |
+
- **고급 설정 섹션**: "고급 설정"
|
| 28 |
+
|
| 29 |
+
### 설정 옵션
|
| 30 |
+
- **시드**: "시드" 및 "시드 랜덤화"
|
| 31 |
+
- **가이던스 스케일**: "가이던스 스케일"
|
| 32 |
+
- **추론 단계**: "추론 단계 수"
|
| 33 |
+
- **프롬프트 재작성**: "프롬프트 재작성"
|
| 34 |
+
|
| 35 |
+
### 예시 섹션
|
| 36 |
+
- **섹션 제목**: "예시"
|
| 37 |
+
- **예시 프롬프트들** (UI에는 한국어 표시, 내부적으로는 영어로 변환하여 처리):
|
| 38 |
+
1. "텍스트를 'COOL NEON SIGN HERE'으로 변경해주세요" → "Change the text to 'COOL NEON SIGN HERE'"
|
| 39 |
+
2. "고양이가 검은색 전통 갓을 쓰고 있는 모습으로 만들어주세요" → "A cat wearing a traditional Korean gat (black wide-brimmed horsehair hat)"
|
| 40 |
+
3. "사진 스타일을 빈티지 만화책 스타일로 바꿔주세요" → "Change the photo style to vintage comic book"
|
| 41 |
+
|
| 42 |
+
### 기술적 변경사항
|
| 43 |
+
- **로고**: Hugging Face resolve URL을 사용하여 로컬 logo.png 파일 참조
|
| 44 |
+
- **정적 파일 서빙**: `gr.set_static_paths()` 추가
|
| 45 |
+
- **설명 텍스트**: GitHub 링크 및 사용 안내를 한국어로 번역
|
| 46 |
+
- **GPU 타임아웃**: 180초(3분)로 설정하여 안정적인 처리 보장
|
| 47 |
+
- **에러 핸들링**: 예외 발생 시 원본 이미지 반환 및 재시도 로직 개선
|
| 48 |
+
- **다운로드 형식**: PNG 형식으로 설정하여 더 나은 이미지 품질 제공
|
| 49 |
+
- **프롬프트 재작성**: API 호출 실패 시 최대 3회 재시도 후 원본 프롬프트 사용
|
| 50 |
+
- **시드 랜덤화**: 기본값으로 활성화되어 매번 다른 결과 생성, 일관된 UI/함수 동작 보장
|
| 51 |
+
- **이중 언어 지원**: 한국어 UI 표시 + 내부적 영어 번역으로 사용자 친화성과 AI 성능을 동시에 최적화
|
| 52 |
+
|
| 53 |
+
## 원본 모델 정보
|
| 54 |
+
|
| 55 |
+
자세한 내용은 [Qwen-Image 시리즈](https://github.com/QwenLM/Qwen-Image)를 참조하세요.
|
| 56 |
+
[Qwen Chat](https://chat.qwen.ai/)에서 체험하거나 [모델을 다운로드](https://huggingface.co/Qwen/Qwen-Image-Edit)하여 ComfyUI나 diffusers로 로컬에서 실행할 수 있습니다.
|
| 57 |
+
|
| 58 |
---
|
| 59 |
|
| 60 |
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
| 61 |
+
|
| 62 |
+
<!-- Force restart -->
|
app.py
ADDED
|
@@ -0,0 +1,320 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import numpy as np
|
| 3 |
+
import random
|
| 4 |
+
import torch
|
| 5 |
+
import spaces
|
| 6 |
+
|
| 7 |
+
from PIL import Image
|
| 8 |
+
from diffusers import QwenImageEditPipeline
|
| 9 |
+
|
| 10 |
+
import os
|
| 11 |
+
import base64
|
| 12 |
+
import json
|
| 13 |
+
|
| 14 |
+
# Set static paths for serving logo
|
| 15 |
+
gr.set_static_paths(paths=["./"])
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
SYSTEM_PROMPT = '''
|
| 19 |
+
# Edit Instruction Rewriter
|
| 20 |
+
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.
|
| 21 |
+
|
| 22 |
+
Please strictly follow the rewriting rules below:
|
| 23 |
+
|
| 24 |
+
## 1. General Principles
|
| 25 |
+
- Keep the rewritten prompt **concise**. Avoid overly long sentences and reduce unnecessary descriptive language.
|
| 26 |
+
- If the instruction is contradictory, vague, or unachievable, prioritize reasonable inference and correction, and supplement details when necessary.
|
| 27 |
+
- Keep the core intention of the original instruction unchanged, only enhancing its clarity, rationality, and visual feasibility.
|
| 28 |
+
- All added objects or modifications must align with the logic and style of the edited input image’s overall scene.
|
| 29 |
+
|
| 30 |
+
## 2. Task Type Handling Rules
|
| 31 |
+
### 1. Add, Delete, Replace Tasks
|
| 32 |
+
- If the instruction is clear (already includes task type, target entity, position, quantity, attributes), preserve the original intent and only refine the grammar.
|
| 33 |
+
- If the description is vague, supplement with minimal but sufficient details (category, color, size, orientation, position, etc.). For example:
|
| 34 |
+
> Original: "Add an animal"
|
| 35 |
+
> Rewritten: "Add a light-gray cat in the bottom-right corner, sitting and facing the camera"
|
| 36 |
+
- Remove meaningless instructions: e.g., "Add 0 objects" should be ignored or flagged as invalid.
|
| 37 |
+
- For replacement tasks, specify "Replace Y with X" and briefly describe the key visual features of X.
|
| 38 |
+
|
| 39 |
+
### 2. Text Editing Tasks
|
| 40 |
+
- All text content must be enclosed in English double quotes `" "`. Do not translate or alter the original language of the text, and do not change the capitalization.
|
| 41 |
+
- **For text replacement tasks, always use the fixed template:**
|
| 42 |
+
- `Replace "xx" to "yy"`.
|
| 43 |
+
- `Replace the xx bounding box to "yy"`.
|
| 44 |
+
- If the user does not specify text content, infer and add concise text based on the instruction and the input image’s context. For example:
|
| 45 |
+
> Original: "Add a line of text" (poster)
|
| 46 |
+
> Rewritten: "Add text \"LIMITED EDITION\" at the top center with slight shadow"
|
| 47 |
+
- Specify text position, color, and layout in a concise way.
|
| 48 |
+
|
| 49 |
+
### 3. Human Editing Tasks
|
| 50 |
+
- Maintain the person’s core visual consistency (ethnicity, gender, age, hairstyle, expression, outfit, etc.).
|
| 51 |
+
- If modifying appearance (e.g., clothes, hairstyle), ensure the new element is consistent with the original style.
|
| 52 |
+
- **For expression changes, they must be natural and subtle, never exaggerated.**
|
| 53 |
+
- If deletion is not specifically emphasized, the most important subject in the original image (e.g., a person, an animal) should be preserved.
|
| 54 |
+
- For background change tasks, emphasize maintaining subject consistency at first.
|
| 55 |
+
- Example:
|
| 56 |
+
> Original: "Change the person’s hat"
|
| 57 |
+
> Rewritten: "Replace the man’s hat with a dark brown beret; keep smile, short hair, and gray jacket unchanged"
|
| 58 |
+
|
| 59 |
+
### 4. Style Transformation or Enhancement Tasks
|
| 60 |
+
- If a style is specified, describe it concisely with key visual traits. For example:
|
| 61 |
+
> Original: "Disco style"
|
| 62 |
+
> Rewritten: "1970s disco: flashing lights, disco ball, mirrored walls, colorful tones"
|
| 63 |
+
- If the instruction says "use reference style" or "keep current style," analyze the input image, extract main features (color, composition, texture, lighting, art style), and integrate them concisely.
|
| 64 |
+
- **For coloring tasks, including restoring old photos, always use the fixed template:** "Restore old photograph, remove scratches, reduce noise, enhance details, high resolution, realistic, natural skin tones, clear facial features, no distortion, vintage photo restoration"
|
| 65 |
+
- If there are other changes, place the style description at the end.
|
| 66 |
+
|
| 67 |
+
## 3. Rationality and Logic Checks
|
| 68 |
+
- Resolve contradictory instructions: e.g., "Remove all trees but keep all trees" should be logically corrected.
|
| 69 |
+
- Add missing key information: if position is unspecified, choose a reasonable area based on composition (near subject, empty space, center/edges).
|
| 70 |
+
|
| 71 |
+
# Output Format Example
|
| 72 |
+
```json
|
| 73 |
+
{
|
| 74 |
+
"Rewritten": "..."
|
| 75 |
+
}
|
| 76 |
+
'''
|
| 77 |
+
|
| 78 |
+
def polish_prompt(prompt, img):
|
| 79 |
+
original_prompt = prompt
|
| 80 |
+
prompt = f"{SYSTEM_PROMPT}\n\nUser Input: {prompt}\n\nRewritten Prompt:"
|
| 81 |
+
success=False
|
| 82 |
+
max_retries = 3
|
| 83 |
+
retry_count = 0
|
| 84 |
+
|
| 85 |
+
while not success and retry_count < max_retries:
|
| 86 |
+
try:
|
| 87 |
+
result = api(prompt, [img])
|
| 88 |
+
# print(f"Result: {result}")
|
| 89 |
+
# print(f"Polished Prompt: {polished_prompt}")
|
| 90 |
+
if isinstance(result, str):
|
| 91 |
+
result = result.replace('```json','')
|
| 92 |
+
result = result.replace('```','')
|
| 93 |
+
result = json.loads(result)
|
| 94 |
+
else:
|
| 95 |
+
result = json.loads(result)
|
| 96 |
+
|
| 97 |
+
polished_prompt = result['Rewritten']
|
| 98 |
+
polished_prompt = polished_prompt.strip()
|
| 99 |
+
polished_prompt = polished_prompt.replace("\n", " ")
|
| 100 |
+
success = True
|
| 101 |
+
except Exception as e:
|
| 102 |
+
print(f"[Warning] Error during API call (attempt {retry_count + 1}): {e}")
|
| 103 |
+
retry_count += 1
|
| 104 |
+
|
| 105 |
+
if not success:
|
| 106 |
+
print(f"[Warning] Failed to polish prompt after {max_retries} attempts, using original prompt")
|
| 107 |
+
return original_prompt
|
| 108 |
+
|
| 109 |
+
return polished_prompt
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def encode_image(pil_image):
|
| 113 |
+
import io
|
| 114 |
+
buffered = io.BytesIO()
|
| 115 |
+
pil_image.save(buffered, format="PNG")
|
| 116 |
+
return base64.b64encode(buffered.getvalue()).decode("utf-8")
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def api(prompt, img_list, model="qwen-vl-max-latest", kwargs={}):
|
| 122 |
+
import dashscope
|
| 123 |
+
api_key = os.environ.get('DASH_API_KEY')
|
| 124 |
+
if not api_key:
|
| 125 |
+
raise EnvironmentError("DASH_API_KEY is not set")
|
| 126 |
+
assert model in ["qwen-vl-max-latest"], f"Not implemented model {model}"
|
| 127 |
+
sys_promot = "you are a helpful assistant, you should provide useful answers to users."
|
| 128 |
+
messages = [
|
| 129 |
+
{"role": "system", "content": sys_promot},
|
| 130 |
+
{"role": "user", "content": []}]
|
| 131 |
+
for img in img_list:
|
| 132 |
+
messages[1]["content"].append(
|
| 133 |
+
{"image": f"data:image/png;base64,{encode_image(img)}"})
|
| 134 |
+
messages[1]["content"].append({"text": f"{prompt}"})
|
| 135 |
+
|
| 136 |
+
response_format = kwargs.get('response_format', None)
|
| 137 |
+
|
| 138 |
+
response = dashscope.MultiModalConversation.call(
|
| 139 |
+
api_key=api_key,
|
| 140 |
+
model=model, # For example, use qwen-plus here. You can change the model name as needed. Model list: https://help.aliyun.com/zh/model-studio/getting-started/models
|
| 141 |
+
messages=messages,
|
| 142 |
+
result_format='message',
|
| 143 |
+
response_format=response_format,
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
if response.status_code == 200:
|
| 147 |
+
return response.output.choices[0].message.content[0]['text']
|
| 148 |
+
else:
|
| 149 |
+
raise Exception(f'Failed to post: {response}')
|
| 150 |
+
|
| 151 |
+
# --- Model Loading ---
|
| 152 |
+
dtype = torch.bfloat16
|
| 153 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 154 |
+
|
| 155 |
+
# Load the model pipeline
|
| 156 |
+
pipe = QwenImageEditPipeline.from_pretrained("Qwen/Qwen-Image-Edit", torch_dtype=dtype).to(device)
|
| 157 |
+
|
| 158 |
+
# --- UI Constants and Helpers ---
|
| 159 |
+
MAX_SEED = np.iinfo(np.int32).max
|
| 160 |
+
|
| 161 |
+
# --- Main Inference Function (with hardcoded negative prompt) ---
|
| 162 |
+
@spaces.GPU(duration=180)
|
| 163 |
+
def infer(
|
| 164 |
+
image,
|
| 165 |
+
prompt,
|
| 166 |
+
seed=0,
|
| 167 |
+
randomize_seed=True,
|
| 168 |
+
true_guidance_scale=1.0,
|
| 169 |
+
num_inference_steps=50,
|
| 170 |
+
rewrite_prompt=True,
|
| 171 |
+
progress=gr.Progress(track_tqdm=True),
|
| 172 |
+
):
|
| 173 |
+
"""
|
| 174 |
+
Generates an image using the local Qwen-Image diffusers pipeline.
|
| 175 |
+
"""
|
| 176 |
+
# Hardcode the negative prompt as requested
|
| 177 |
+
negative_prompt = " "
|
| 178 |
+
|
| 179 |
+
if randomize_seed:
|
| 180 |
+
seed = random.randint(0, MAX_SEED)
|
| 181 |
+
|
| 182 |
+
# Set up the generator for reproducibility
|
| 183 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 184 |
+
|
| 185 |
+
# Translate Korean example prompts to English for better AI performance
|
| 186 |
+
korean_to_english_examples = {
|
| 187 |
+
"텍스트를 'COOL NEON SIGN HERE'으로 변경해주세요": "Change the text to 'COOL NEON SIGN HERE'",
|
| 188 |
+
"고양이가 검은색 전통 갓을 쓰고 있는 모습으로 만들어주세요": "A cat wearing a traditional Korean gat (black wide-brimmed horsehair hat)",
|
| 189 |
+
"사진 스타일을 빈티지 만화책 스타일로 바꿔주세요": "Change the photo style to vintage comic book"
|
| 190 |
+
}
|
| 191 |
+
|
| 192 |
+
# Use English version if this is one of our Korean examples
|
| 193 |
+
if prompt in korean_to_english_examples:
|
| 194 |
+
original_prompt = prompt
|
| 195 |
+
prompt = korean_to_english_examples[prompt]
|
| 196 |
+
print(f"Translated Korean example: '{original_prompt}' -> '{prompt}'")
|
| 197 |
+
|
| 198 |
+
print(f"Calling pipeline with prompt: '{prompt}'")
|
| 199 |
+
print(f"Negative Prompt: '{negative_prompt}'")
|
| 200 |
+
print(f"Seed: {seed}, Steps: {num_inference_steps}, Guidance: {true_guidance_scale}")
|
| 201 |
+
try:
|
| 202 |
+
if rewrite_prompt:
|
| 203 |
+
prompt = polish_prompt(prompt, image)
|
| 204 |
+
print(f"Rewritten Prompt: {prompt}")
|
| 205 |
+
|
| 206 |
+
# Generate the image
|
| 207 |
+
images = pipe(
|
| 208 |
+
image,
|
| 209 |
+
prompt=prompt,
|
| 210 |
+
negative_prompt=negative_prompt,
|
| 211 |
+
num_inference_steps=num_inference_steps,
|
| 212 |
+
generator=generator,
|
| 213 |
+
true_cfg_scale=true_guidance_scale,
|
| 214 |
+
num_images_per_prompt=1
|
| 215 |
+
).images
|
| 216 |
+
|
| 217 |
+
return images[0], seed
|
| 218 |
+
|
| 219 |
+
except Exception as e:
|
| 220 |
+
print(f"Error during inference: {e}")
|
| 221 |
+
# Return the original image with error message
|
| 222 |
+
return image, seed
|
| 223 |
+
|
| 224 |
+
# --- Examples and UI Layout ---
|
| 225 |
+
examples = []
|
| 226 |
+
|
| 227 |
+
css = """
|
| 228 |
+
#col-container {
|
| 229 |
+
margin: 0 auto;
|
| 230 |
+
max-width: 1024px;
|
| 231 |
+
}
|
| 232 |
+
#edit_text{
|
| 233 |
+
margin-top: -62px !important
|
| 234 |
+
}
|
| 235 |
+
"""
|
| 236 |
+
|
| 237 |
+
with gr.Blocks(css=css) as demo:
|
| 238 |
+
with gr.Column(elem_id="col-container"):
|
| 239 |
+
gr.HTML('<h1 style="text-align: center; color: #6366f1; font-size: 3rem; font-weight: bold; margin: 2rem 0; font-family: system-ui, -apple-system, sans-serif; display: flex; align-items: center; justify-content: center; gap: 1rem;"><img src="https://huggingface.co/spaces/tchung1970/Qwen-Image-Edit/resolve/main/logo.png" alt="로고" style="height: 3rem; width: auto;"> 퀀 이미지 편집기</h1>')
|
| 240 |
+
gr.Markdown("[더 알아보기](https://github.com/QwenLM/Qwen-Image)에서 Qwen-Image 시리즈에 대해 자세히 알아보세요. [Qwen Chat](https://chat.qwen.ai/)에서 체험하거나 [모델 다운로드](https://huggingface.co/Qwen/Qwen-Image-Edit)하여 ComfyUI나 diffusers로 로컬에서 실행해보세요.")
|
| 241 |
+
with gr.Row():
|
| 242 |
+
with gr.Column():
|
| 243 |
+
input_image = gr.Image(
|
| 244 |
+
label="입력 이미지",
|
| 245 |
+
show_label=False,
|
| 246 |
+
type="pil",
|
| 247 |
+
placeholder="이미지를 여기로 끌어다 놓으세요\n- 또는 -\n업로드하려면 클릭하세요"
|
| 248 |
+
)
|
| 249 |
+
|
| 250 |
+
result = gr.Image(label="결과", show_label=False, type="pil", format="png")
|
| 251 |
+
with gr.Row():
|
| 252 |
+
prompt = gr.Text(
|
| 253 |
+
label="프롬프트",
|
| 254 |
+
show_label=False,
|
| 255 |
+
placeholder="편집 지시사항을 설명해주세요",
|
| 256 |
+
container=False,
|
| 257 |
+
)
|
| 258 |
+
run_button = gr.Button("편집!", variant="primary")
|
| 259 |
+
|
| 260 |
+
with gr.Accordion("고급 설정", open=False):
|
| 261 |
+
# Negative prompt UI element is removed here
|
| 262 |
+
|
| 263 |
+
seed = gr.Slider(
|
| 264 |
+
label="시드",
|
| 265 |
+
minimum=0,
|
| 266 |
+
maximum=MAX_SEED,
|
| 267 |
+
step=1,
|
| 268 |
+
value=0,
|
| 269 |
+
)
|
| 270 |
+
|
| 271 |
+
randomize_seed = gr.Checkbox(label="시드 랜덤화", value=True)
|
| 272 |
+
|
| 273 |
+
with gr.Row():
|
| 274 |
+
|
| 275 |
+
true_guidance_scale = gr.Slider(
|
| 276 |
+
label="가이던스 스케일",
|
| 277 |
+
minimum=1.0,
|
| 278 |
+
maximum=10.0,
|
| 279 |
+
step=0.1,
|
| 280 |
+
value=4.0
|
| 281 |
+
)
|
| 282 |
+
|
| 283 |
+
num_inference_steps = gr.Slider(
|
| 284 |
+
label="추론 단계 수",
|
| 285 |
+
minimum=1,
|
| 286 |
+
maximum=50,
|
| 287 |
+
step=1,
|
| 288 |
+
value=50,
|
| 289 |
+
)
|
| 290 |
+
|
| 291 |
+
rewrite_prompt = gr.Checkbox(label="프롬프트 재작성", value=True)
|
| 292 |
+
|
| 293 |
+
gr.Examples(
|
| 294 |
+
label="예시",
|
| 295 |
+
examples=[
|
| 296 |
+
["neon_sign.png", "텍스트를 'COOL NEON SIGN HERE'으로 변경해주세요"],
|
| 297 |
+
["cat_sitting.jpg", "고양이가 검은색 전통 갓을 쓰고 있는 모습으로 만들어주세요"],
|
| 298 |
+
["pie.png", "사진 스타일을 빈티지 만화책 스타일로 바꿔주세요"]],
|
| 299 |
+
inputs=[input_image, prompt],
|
| 300 |
+
outputs=[result, seed],
|
| 301 |
+
fn=infer,
|
| 302 |
+
cache_examples="lazy")
|
| 303 |
+
|
| 304 |
+
gr.on(
|
| 305 |
+
triggers=[run_button.click, prompt.submit],
|
| 306 |
+
fn=infer,
|
| 307 |
+
inputs=[
|
| 308 |
+
input_image,
|
| 309 |
+
prompt,
|
| 310 |
+
seed,
|
| 311 |
+
randomize_seed,
|
| 312 |
+
true_guidance_scale,
|
| 313 |
+
num_inference_steps,
|
| 314 |
+
rewrite_prompt,
|
| 315 |
+
],
|
| 316 |
+
outputs=[result, seed],
|
| 317 |
+
)
|
| 318 |
+
|
| 319 |
+
if __name__ == "__main__":
|
| 320 |
+
demo.launch()
|
cat_sitting.jpg
ADDED
|
Git LFS Details
|
logo.png
ADDED
|
Git LFS Details
|
neon_sign.png
ADDED
|
Git LFS Details
|
pie.png
ADDED
|
Git LFS Details
|
requirements.txt
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Force rebuild
|
| 2 |
+
git+https://github.com/huggingface/diffusers.git
|
| 3 |
+
|
| 4 |
+
transformers
|
| 5 |
+
accelerate
|
| 6 |
+
safetensors
|
| 7 |
+
sentencepiece
|
| 8 |
+
dashscope
|
| 9 |
+
torchvision
|