Spaces:
Sleeping
Sleeping
Commit ·
0c28cde
1
Parent(s): 240d9c7
Add real PlotCraft model inference path
Browse files- app.py +4 -1
- requirements.txt +3 -0
- src/plotcraft/config.py +19 -0
- src/plotcraft/model.py +79 -0
- src/plotcraft/service.py +37 -3
- tests/test_service.py +11 -2
app.py
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
|
| 3 |
from src.plotcraft.service import generate_plot_code
|
|
@@ -10,6 +12,7 @@ def handle_generation(prompt: str) -> str:
|
|
| 10 |
except ValueError as error:
|
| 11 |
return str(error)
|
| 12 |
except Exception:
|
|
|
|
| 13 |
return "Plot generation failed. Please try again."
|
| 14 |
|
| 15 |
|
|
@@ -37,4 +40,4 @@ demo = gr.Interface(
|
|
| 37 |
|
| 38 |
|
| 39 |
if __name__ == "__main__":
|
| 40 |
-
demo.launch()
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
|
| 3 |
import gradio as gr
|
| 4 |
|
| 5 |
from src.plotcraft.service import generate_plot_code
|
|
|
|
| 12 |
except ValueError as error:
|
| 13 |
return str(error)
|
| 14 |
except Exception:
|
| 15 |
+
logging.exception("Plot generation failed")
|
| 16 |
return "Plot generation failed. Please try again."
|
| 17 |
|
| 18 |
|
|
|
|
| 40 |
|
| 41 |
|
| 42 |
if __name__ == "__main__":
|
| 43 |
+
demo.launch()
|
requirements.txt
CHANGED
|
@@ -1,4 +1,5 @@
|
|
| 1 |
annotated-doc==0.0.5
|
|
|
|
| 2 |
annotated-types==0.8.0
|
| 3 |
anyio==4.15.1
|
| 4 |
brotli==1.2.0
|
|
@@ -35,6 +36,8 @@ pydantic_core==2.46.5
|
|
| 35 |
pydub==0.25.1
|
| 36 |
Pygments==2.21.0
|
| 37 |
pytest==9.1.1
|
|
|
|
|
|
|
| 38 |
python-dateutil==2.9.0.post0
|
| 39 |
python-multipart==0.0.32
|
| 40 |
pytz==2026.4
|
|
|
|
| 1 |
annotated-doc==0.0.5
|
| 2 |
+
accelerate>=1.0,<2
|
| 3 |
annotated-types==0.8.0
|
| 4 |
anyio==4.15.1
|
| 5 |
brotli==1.2.0
|
|
|
|
| 36 |
pydub==0.25.1
|
| 37 |
Pygments==2.21.0
|
| 38 |
pytest==9.1.1
|
| 39 |
+
torch>=2.8,<3
|
| 40 |
+
transformers==5.2.0
|
| 41 |
python-dateutil==2.9.0.post0
|
| 42 |
python-multipart==0.0.32
|
| 43 |
pytz==2026.4
|
src/plotcraft/config.py
CHANGED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Runtime configuration for PlotCraft."""
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
MODEL_ID = os.getenv("MODEL_ID", "saeedbenadeeb/NLG_Project")
|
| 7 |
+
MODEL_SUBFOLDER = os.getenv("MODEL_SUBFOLDER", "grpo-qwen2.5-3b")
|
| 8 |
+
MODEL_MODE = os.getenv("MODEL_MODE", "mock").lower()
|
| 9 |
+
MAX_NEW_TOKENS = int(os.getenv("MAX_NEW_TOKENS", "1024"))
|
| 10 |
+
MAX_PROMPT_CHARACTERS = int(os.getenv("MAX_PROMPT_CHARACTERS", "2000"))
|
| 11 |
+
|
| 12 |
+
SYSTEM_PROMPT = os.getenv(
|
| 13 |
+
"SYSTEM_PROMPT",
|
| 14 |
+
(
|
| 15 |
+
"You are PlotCraft, an assistant that converts visualization requests "
|
| 16 |
+
"into executable Matplotlib or TikZ code. Return only the requested "
|
| 17 |
+
"code without Markdown fences or additional explanation."
|
| 18 |
+
),
|
| 19 |
+
)
|
src/plotcraft/model.py
CHANGED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Load the trained PlotCraft model and run inference."""
|
| 2 |
+
|
| 3 |
+
from functools import lru_cache
|
| 4 |
+
from typing import Any
|
| 5 |
+
|
| 6 |
+
from src.plotcraft.config import (
|
| 7 |
+
MAX_NEW_TOKENS,
|
| 8 |
+
MODEL_ID,
|
| 9 |
+
MODEL_SUBFOLDER,
|
| 10 |
+
SYSTEM_PROMPT,
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
@lru_cache(maxsize=1)
|
| 15 |
+
def load_model() -> tuple[Any, Any]:
|
| 16 |
+
"""Download and load the tokenizer and full GRPO model once."""
|
| 17 |
+
try:
|
| 18 |
+
import torch
|
| 19 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 20 |
+
except ImportError as error:
|
| 21 |
+
raise RuntimeError(
|
| 22 |
+
"Real model mode requires torch, transformers, and accelerate."
|
| 23 |
+
) from error
|
| 24 |
+
|
| 25 |
+
if not torch.cuda.is_available():
|
| 26 |
+
raise RuntimeError(
|
| 27 |
+
"Real model mode requires a CUDA GPU. Use MODEL_MODE=mock locally."
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
compute_dtype = (
|
| 31 |
+
torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 35 |
+
MODEL_ID,
|
| 36 |
+
subfolder=MODEL_SUBFOLDER,
|
| 37 |
+
)
|
| 38 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 39 |
+
MODEL_ID,
|
| 40 |
+
subfolder=MODEL_SUBFOLDER,
|
| 41 |
+
dtype=compute_dtype,
|
| 42 |
+
device_map="auto",
|
| 43 |
+
low_cpu_mem_usage=True,
|
| 44 |
+
)
|
| 45 |
+
model.eval()
|
| 46 |
+
return tokenizer, model
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def generate_with_model(prompt: str) -> str:
|
| 50 |
+
"""Generate PlotCraft code with the full GRPO Qwen model."""
|
| 51 |
+
import torch
|
| 52 |
+
|
| 53 |
+
tokenizer, model = load_model()
|
| 54 |
+
messages = [
|
| 55 |
+
{"role": "system", "content": SYSTEM_PROMPT},
|
| 56 |
+
{"role": "user", "content": prompt},
|
| 57 |
+
]
|
| 58 |
+
formatted_prompt = tokenizer.apply_chat_template(
|
| 59 |
+
messages,
|
| 60 |
+
tokenize=False,
|
| 61 |
+
add_generation_prompt=True,
|
| 62 |
+
)
|
| 63 |
+
inputs = tokenizer(formatted_prompt, return_tensors="pt").to(model.device)
|
| 64 |
+
|
| 65 |
+
with torch.inference_mode():
|
| 66 |
+
output_ids = model.generate(
|
| 67 |
+
**inputs,
|
| 68 |
+
max_new_tokens=MAX_NEW_TOKENS,
|
| 69 |
+
do_sample=True,
|
| 70 |
+
temperature=0.7,
|
| 71 |
+
top_p=0.8,
|
| 72 |
+
top_k=20,
|
| 73 |
+
repetition_penalty=1.05,
|
| 74 |
+
pad_token_id=tokenizer.pad_token_id,
|
| 75 |
+
eos_token_id=tokenizer.eos_token_id,
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
new_tokens = output_ids[0, inputs["input_ids"].shape[1] :]
|
| 79 |
+
return tokenizer.decode(new_tokens, skip_special_tokens=True).strip()
|
src/plotcraft/service.py
CHANGED
|
@@ -1,3 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
PLACEHOLDER_CODE = """import matplotlib.pyplot as plt
|
| 2 |
|
| 3 |
categories = ["Model A", "Model B", "Model C"]
|
|
@@ -11,12 +16,41 @@ plt.show()
|
|
| 11 |
"""
|
| 12 |
|
| 13 |
|
| 14 |
-
def
|
| 15 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
|
|
|
|
|
|
|
|
|
| 17 |
cleaned_prompt = prompt.strip()
|
| 18 |
|
| 19 |
if not cleaned_prompt:
|
| 20 |
raise ValueError("Please enter a plotting request.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Application-level validation and PlotCraft generation service."""
|
| 2 |
+
|
| 3 |
+
from src.plotcraft.config import MAX_PROMPT_CHARACTERS, MODEL_MODE
|
| 4 |
+
|
| 5 |
+
|
| 6 |
PLACEHOLDER_CODE = """import matplotlib.pyplot as plt
|
| 7 |
|
| 8 |
categories = ["Model A", "Model B", "Model C"]
|
|
|
|
| 16 |
"""
|
| 17 |
|
| 18 |
|
| 19 |
+
def _remove_markdown_fences(generated_text: str) -> str:
|
| 20 |
+
"""Remove a single Markdown code fence around generated code."""
|
| 21 |
+
cleaned = generated_text.strip()
|
| 22 |
+
if not cleaned.startswith("```"):
|
| 23 |
+
return cleaned
|
| 24 |
+
|
| 25 |
+
lines = cleaned.splitlines()
|
| 26 |
+
if lines and lines[0].startswith("```"):
|
| 27 |
+
lines = lines[1:]
|
| 28 |
+
if lines and lines[-1].strip() == "```":
|
| 29 |
+
lines = lines[:-1]
|
| 30 |
+
return "\n".join(lines).strip()
|
| 31 |
|
| 32 |
+
|
| 33 |
+
def generate_plot_code(prompt: str) -> str:
|
| 34 |
+
"""Validate a request and return plotting code."""
|
| 35 |
cleaned_prompt = prompt.strip()
|
| 36 |
|
| 37 |
if not cleaned_prompt:
|
| 38 |
raise ValueError("Please enter a plotting request.")
|
| 39 |
+
if len(cleaned_prompt) > MAX_PROMPT_CHARACTERS:
|
| 40 |
+
raise ValueError(
|
| 41 |
+
f"Please keep the request under {MAX_PROMPT_CHARACTERS} characters."
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
if MODEL_MODE == "mock":
|
| 45 |
+
return PLACEHOLDER_CODE
|
| 46 |
+
if MODEL_MODE != "real":
|
| 47 |
+
raise RuntimeError("MODEL_MODE must be either 'mock' or 'real'.")
|
| 48 |
+
|
| 49 |
+
from src.plotcraft.model import generate_with_model
|
| 50 |
|
| 51 |
+
generated_code = _remove_markdown_fences(
|
| 52 |
+
generate_with_model(cleaned_prompt)
|
| 53 |
+
)
|
| 54 |
+
if not generated_code:
|
| 55 |
+
raise RuntimeError("The model returned an empty response.")
|
| 56 |
+
return generated_code
|
tests/test_service.py
CHANGED
|
@@ -1,6 +1,9 @@
|
|
| 1 |
import pytest
|
| 2 |
|
| 3 |
-
from src.plotcraft.service import
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
|
| 6 |
def test_generate_plot_code_returns_python_code():
|
|
@@ -16,4 +19,10 @@ def test_generate_plot_code_rejects_empty_prompt():
|
|
| 16 |
ValueError,
|
| 17 |
match="Please enter a plotting request",
|
| 18 |
):
|
| 19 |
-
generate_plot_code(" ")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import pytest
|
| 2 |
|
| 3 |
+
from src.plotcraft.service import (
|
| 4 |
+
_remove_markdown_fences,
|
| 5 |
+
generate_plot_code,
|
| 6 |
+
)
|
| 7 |
|
| 8 |
|
| 9 |
def test_generate_plot_code_returns_python_code():
|
|
|
|
| 19 |
ValueError,
|
| 20 |
match="Please enter a plotting request",
|
| 21 |
):
|
| 22 |
+
generate_plot_code(" ")
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def test_remove_markdown_fences():
|
| 26 |
+
result = _remove_markdown_fences("```python\nprint('plot')\n```")
|
| 27 |
+
|
| 28 |
+
assert result == "print('plot')"
|