rahul7star commited on
Commit
139a0fa
·
verified ·
1 Parent(s): e725ad5

Update app_cpu.py

Browse files
Files changed (1) hide show
  1. 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 huggingface_hub import snapshot_download
7
-
8
- # ============================================================
9
- # 1️⃣ Pre-download model during app startup
10
- # ============================================================
11
-
12
- DEFAULT_MODEL_REPO = os.environ.get("MODEL_OUTPUT_PATH", "rubricreward/mR3-Qwen3-14B-en-prompt-en-thinking")
13
-
14
- print(f"🔄 Checking and downloading model repo: {DEFAULT_MODEL_REPO}")
15
- local_model_dir = snapshot_download(repo_id=DEFAULT_MODEL_REPO)
16
- print(f"✅ Model cached locally at: {local_model_dir}")
17
-
18
- # ============================================================
19
- # 2️⃣ Utilities
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
- generated_ids_trimmed = [
101
- out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
 
102
  ]
103
 
104
- output_text = processor.batch_decode(
105
- generated_ids_trimmed,
106
- skip_special_tokens=True,
107
- clean_up_tokenization_spaces=False,
 
 
 
 
 
 
 
 
 
 
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
- sys_prompt = gr.Textbox(
157
- label="System Prompt",
158
- value="Please think step-by-step and rewrite the user’s prompt in a more refined, creative, and detailed way:",
159
- lines=3
160
- )
161
- temperature = gr.Slider(0, 1, value=0.1, step=0.05, label="Temperature")
162
- max_new_tokens = gr.Slider(16, 4096, value=2048, step=16, label="Max New Tokens")
163
- torch_dtype = gr.Dropdown(["float32", "float16", "bfloat16"], value="float32", label="Torch Dtype")
164
-
165
- state = gr.State(value=None)
166
-
167
- with gr.Tab("Inference"):
168
- with gr.Row():
169
- with gr.Column(scale=2):
170
- prompt = gr.Textbox(label="Input Prompt", lines=6, placeholder="Paste the prompt to rewrite here...")
171
- run_btn = gr.Button("Generate Rewrite", variant="primary")
172
- gr.Examples(examples=example_prompts, inputs=prompt)
173
- with gr.Column(scale=3):
174
- out_text = gr.Textbox(label="Rewritten Prompt", lines=10)
175
- out_info = gr.Markdown("✅ Model loaded on CPU (from `snapshot_download` cache).")
176
-
177
- run_btn.click(
178
- run_single,
179
- inputs=[prompt, sys_prompt, temperature, max_new_tokens, torch_dtype, state],
180
- outputs=[out_text, out_info, state]
181
- )
182
 
 
 
 
183
  if __name__ == "__main__":
184
- demo.launch(show_error=True, share=True)
 
 
 
 
 
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()