Update app_cpu.py
Browse files- app_cpu.py +62 -175
app_cpu.py
CHANGED
|
@@ -1,184 +1,71 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import time
|
| 3 |
-
import logging
|
| 4 |
-
import re
|
| 5 |
import gradio as gr
|
| 6 |
-
from
|
| 7 |
-
|
| 8 |
-
#
|
| 9 |
-
#
|
| 10 |
-
#
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
#
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
try:
|
| 23 |
-
from qwen_vl_utils import process_vision_info
|
| 24 |
-
except Exception:
|
| 25 |
-
def process_vision_info(messages):
|
| 26 |
-
return None, None
|
| 27 |
-
|
| 28 |
-
def replace_single_quotes(text):
|
| 29 |
-
"""Replace single quotes inside words with double quotes for consistency."""
|
| 30 |
-
pattern = r"\B'([^']*)'\B"
|
| 31 |
-
replaced_text = re.sub(pattern, r'"\1"', text)
|
| 32 |
-
return replaced_text.replace("’", "”").replace("‘", "“")
|
| 33 |
-
|
| 34 |
-
def _str_to_dtype(dtype_str):
|
| 35 |
-
"""Normalize torch dtype string."""
|
| 36 |
-
return dtype_str if dtype_str in ("bfloat16", "float16", "float32") else "float32"
|
| 37 |
-
|
| 38 |
-
# ============================================================
|
| 39 |
-
# 3️⃣ Load model once (from local snapshot)
|
| 40 |
-
# ============================================================
|
| 41 |
-
|
| 42 |
-
import torch
|
| 43 |
-
from transformers import Qwen2_5_VLForConditionalGeneration, AutoProcessor
|
| 44 |
-
|
| 45 |
-
logging.basicConfig(level=logging.INFO)
|
| 46 |
-
logger = logging.getLogger("PromptEnhancerCPU")
|
| 47 |
-
|
| 48 |
-
dtype = torch.float32 # Default for CPU
|
| 49 |
-
logger.info("🔧 Loading pre-downloaded model from local path...")
|
| 50 |
-
|
| 51 |
-
model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
|
| 52 |
-
local_model_dir,
|
| 53 |
-
torch_dtype=dtype,
|
| 54 |
-
device_map={"": "cpu"}, # Force CPU only
|
| 55 |
-
attn_implementation="sdpa",
|
| 56 |
-
)
|
| 57 |
-
processor = AutoProcessor.from_pretrained(local_model_dir)
|
| 58 |
-
|
| 59 |
-
logger.info("✅ Model loaded and ready on CPU.")
|
| 60 |
-
|
| 61 |
-
# ============================================================
|
| 62 |
-
# 4️⃣ Inference (uses already-loaded model)
|
| 63 |
-
# ============================================================
|
| 64 |
-
|
| 65 |
-
def cpu_predict(prompt_cot, sys_prompt, temperature, max_new_tokens, torch_dtype):
|
| 66 |
-
"""Generate rewritten prompt using preloaded model on CPU."""
|
| 67 |
-
dtype = {
|
| 68 |
-
"bfloat16": torch.bfloat16,
|
| 69 |
-
"float16": torch.float16,
|
| 70 |
-
"float32": torch.float32,
|
| 71 |
-
}.get(torch_dtype, torch.float32)
|
| 72 |
-
|
| 73 |
-
device = "cpu"
|
| 74 |
-
|
| 75 |
-
org_prompt_cot = prompt_cot
|
| 76 |
-
user_prompt_format = sys_prompt + "\n" + org_prompt_cot
|
| 77 |
-
messages = [{"role": "user", "content": [{"type": "text", "text": user_prompt_format}]}]
|
| 78 |
-
|
| 79 |
-
text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 80 |
-
image_inputs, video_inputs = process_vision_info(messages)
|
| 81 |
-
|
| 82 |
-
inputs = processor(
|
| 83 |
-
text=[text],
|
| 84 |
-
images=image_inputs,
|
| 85 |
-
videos=video_inputs,
|
| 86 |
-
padding=True,
|
| 87 |
-
return_tensors="pt",
|
| 88 |
-
).to(device)
|
| 89 |
-
|
| 90 |
-
logger.info("🧠 Running generation (CPU)...")
|
| 91 |
-
generated_ids = model.generate(
|
| 92 |
-
**inputs,
|
| 93 |
-
max_new_tokens=int(max_new_tokens),
|
| 94 |
-
temperature=float(temperature),
|
| 95 |
-
do_sample=False,
|
| 96 |
-
top_k=5,
|
| 97 |
-
top_p=0.9,
|
| 98 |
-
)
|
| 99 |
|
| 100 |
-
|
| 101 |
-
|
|
|
|
| 102 |
]
|
| 103 |
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
)
|
| 109 |
-
output_res = output_text[0]
|
| 110 |
|
| 111 |
-
try:
|
| 112 |
-
# Extract part after "think>" if present
|
| 113 |
-
assert output_res.count("think>") == 2
|
| 114 |
-
new_prompt = output_res.split("think>")[-1].lstrip("\n")
|
| 115 |
-
new_prompt = replace_single_quotes(new_prompt)
|
| 116 |
-
except Exception:
|
| 117 |
-
new_prompt = org_prompt_cot
|
| 118 |
-
|
| 119 |
-
return new_prompt, ""
|
| 120 |
-
|
| 121 |
-
# ============================================================
|
| 122 |
-
# 5️⃣ Gradio Logic
|
| 123 |
-
# ============================================================
|
| 124 |
-
|
| 125 |
-
def run_single(prompt, sys_prompt, temperature, max_new_tokens, torch_dtype, state):
|
| 126 |
-
"""Handle one user query from Gradio."""
|
| 127 |
-
if not prompt.strip():
|
| 128 |
-
return "", "Please enter a prompt first.", state
|
| 129 |
-
|
| 130 |
-
t0 = time.time()
|
| 131 |
-
try:
|
| 132 |
-
new_prompt, err = cpu_predict(prompt, sys_prompt, temperature, max_new_tokens, torch_dtype)
|
| 133 |
-
dt = time.time() - t0
|
| 134 |
-
msg = f"Time taken: {dt:.2f}s"
|
| 135 |
-
if err:
|
| 136 |
-
msg = f"{err} ({msg})"
|
| 137 |
-
return new_prompt, msg, state
|
| 138 |
-
except Exception as e:
|
| 139 |
-
return "", f"Error: {e}", state
|
| 140 |
-
|
| 141 |
-
# ============================================================
|
| 142 |
-
# 6️⃣ Gradio UI
|
| 143 |
-
# ============================================================
|
| 144 |
-
|
| 145 |
-
example_prompts = [
|
| 146 |
-
"Third-person view: a race car speeding through a city track, with a mini-map in the top-left corner and a speedometer in the bottom-right.",
|
| 147 |
-
"Anime-style portrait of a girl with short purple hair and soft lighting.",
|
| 148 |
-
"Pointillism painting: two fishermen carrying crates by the seaside, with boats docked nearby.",
|
| 149 |
-
"A Van Gogh-inspired wheat field tangled with swirling blue nebulae and fiery sunflowers.",
|
| 150 |
-
"Create a painting depicting a 30-year-old businesswoman on a plane trip.",
|
| 151 |
-
]
|
| 152 |
-
|
| 153 |
-
with gr.Blocks(title="Prompt Enhancer (CPU Preload)") as demo:
|
| 154 |
-
gr.Markdown("## 🧩 Prompt Enhancer (CPU Mode — Model Preloaded via `snapshot_download`)")
|
| 155 |
with gr.Row():
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
)
|
| 182 |
|
|
|
|
|
|
|
|
|
|
| 183 |
if __name__ == "__main__":
|
| 184 |
-
demo.launch(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
|
| 3 |
+
|
| 4 |
+
# =========================================================
|
| 5 |
+
# Load model and tokenizer
|
| 6 |
+
# =========================================================
|
| 7 |
+
MODEL_ID = "gokaygokay/prompt-enhancer-gemma-3-270m-it"
|
| 8 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
|
| 9 |
+
model = AutoModelForCausalLM.from_pretrained(MODEL_ID)
|
| 10 |
+
pipe = pipeline("text-generation", model=model, tokenizer=tokenizer)
|
| 11 |
+
|
| 12 |
+
# =========================================================
|
| 13 |
+
# Define enhancer function
|
| 14 |
+
# =========================================================
|
| 15 |
+
def enhance_prompt(prompt: str):
|
| 16 |
+
if not prompt.strip():
|
| 17 |
+
return "⚠️ Please enter a prompt to enhance."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
+
messages = [
|
| 20 |
+
{"role": "system", "content": "Enhance and expand the following prompt with more details and context:"},
|
| 21 |
+
{"role": "user", "content": prompt.strip()},
|
| 22 |
]
|
| 23 |
|
| 24 |
+
chat_input = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 25 |
+
output = pipe(chat_input, max_new_tokens=256, do_sample=True, temperature=0.8)
|
| 26 |
+
result = output[0]["generated_text"]
|
| 27 |
+
return result.strip()
|
| 28 |
+
|
| 29 |
+
# =========================================================
|
| 30 |
+
# Gradio UI
|
| 31 |
+
# =========================================================
|
| 32 |
+
with gr.Blocks(theme=gr.themes.Soft(), title="Prompt Enhancer ✨") as demo:
|
| 33 |
+
gr.Markdown(
|
| 34 |
+
"""
|
| 35 |
+
# ✨ Prompt Enhancer — Gemma 3 270M IT
|
| 36 |
+
Enhance and expand your prompts with creative detail and context using a small, efficient language model.
|
| 37 |
+
"""
|
| 38 |
)
|
|
|
|
| 39 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
with gr.Row():
|
| 41 |
+
with gr.Column(scale=1):
|
| 42 |
+
input_text = gr.Textbox(
|
| 43 |
+
label="Enter your prompt",
|
| 44 |
+
placeholder="e.g. a cat sitting on a chair",
|
| 45 |
+
lines=4,
|
| 46 |
+
)
|
| 47 |
+
enhance_button = gr.Button("🚀 Enhance Prompt", variant="primary")
|
| 48 |
+
with gr.Column(scale=1):
|
| 49 |
+
output_text = gr.Textbox(
|
| 50 |
+
label="Enhanced Prompt",
|
| 51 |
+
placeholder="Your enhanced prompt will appear here...",
|
| 52 |
+
lines=8,
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
enhance_button.click(enhance_prompt, inputs=input_text, outputs=output_text)
|
| 56 |
+
|
| 57 |
+
gr.Markdown(
|
| 58 |
+
"""
|
| 59 |
+
---
|
| 60 |
+
🧠 **Tip:** Try short creative prompts like
|
| 61 |
+
- “a futuristic city at sunset”
|
| 62 |
+
- “a woman reading under a tree”
|
| 63 |
+
- “a magical forest with glowing mushrooms”
|
| 64 |
+
"""
|
| 65 |
+
)
|
|
|
|
| 66 |
|
| 67 |
+
# =========================================================
|
| 68 |
+
# Launch the app
|
| 69 |
+
# =========================================================
|
| 70 |
if __name__ == "__main__":
|
| 71 |
+
demo.launch()
|