File size: 9,316 Bytes
d74777b
 
 
 
 
 
 
 
 
2e37b27
d74777b
 
 
2e37b27
 
 
6db5389
e26444e
6db5389
d74777b
a73f2ec
d74777b
cf6c23e
 
d74777b
 
cf6c23e
 
d74777b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf6c23e
d74777b
 
 
 
 
cf6c23e
 
d74777b
cf6c23e
 
 
 
 
 
 
 
 
d74777b
cf6c23e
d74777b
 
 
 
cf6c23e
 
d74777b
 
cf6c23e
 
 
d74777b
cf6c23e
d74777b
 
 
 
 
ee83bcc
d74777b
 
 
 
 
 
 
 
 
 
 
24210de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf6c23e
758c89b
24210de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e26444e
 
d74777b
24210de
 
 
 
 
d74777b
 
 
 
 
e26444e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
562bd04
 
e26444e
 
 
 
d74777b
 
 
 
 
 
 
cf6c23e
d74777b
 
 
7dd9329
 
 
 
 
 
 
 
 
690854e
ad1a51d
7dd9329
 
9beab62
 
7dd9329
0a1f3da
 
cf6c23e
 
0a1f3da
d74777b
0a1f3da
 
 
d74777b
 
 
 
 
9beab62
 
 
 
 
 
 
 
c406285
 
d74777b
 
 
cf6c23e
 
1dc498f
 
 
d74777b
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
"""CodeWraith HuggingFace Spaces entry point.

Downloads the LoRA adapter from HF Hub and serves the Gradio interface.
Set HF_REPO_ID environment variable to point to your uploaded adapter.
"""

from __future__ import annotations

import os
import sys
from pathlib import Path
from typing import Any

# Ensure src/ is importable (HF Spaces runs app.py directly)
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src"))

# Force pandas to fully initialize before transitive imports cause circular import
import pandas  # noqa: F401, I001

import gradio as gr
import spaces

from codewraith import SYSTEM_MESSAGE

# --- Config ---

HF_REPO_ID = os.environ.get("HF_REPO_ID", "slenk/codewraith-lora-8b")
MODEL_KEY = os.environ.get("MODEL_KEY", "8b")
ADAPTER_DIR = "./adapter"

MODELS = {
    "3b": "unsloth/Llama-3.2-3B-Instruct",
    "8b": "unsloth/Llama-3.1-8B-Instruct",
}

EXAMPLE_CODE = '''\
def fibonacci(n: int) -> list[int]:
    """Generate the first n Fibonacci numbers."""
    if n <= 0:
        return []
    sequence = [0, 1]
    while len(sequence) < n:
        sequence.append(sequence[-1] + sequence[-2])
    return sequence[:n]
'''

# --- Global state ---

_model = None
_tokenizer = None
_retriever = None


# --- Model loading ---


def download_adapter():
    """Download the LoRA adapter from HF Hub if not already cached."""
    if Path(ADAPTER_DIR).exists() and any(Path(ADAPTER_DIR).iterdir()):
        print(f"Adapter already cached at {ADAPTER_DIR}")
        return

    from huggingface_hub import snapshot_download

    print(f"Downloading adapter from {HF_REPO_ID}...")
    snapshot_download(repo_id=HF_REPO_ID, local_dir=ADAPTER_DIR)
    print("Download complete.")


def load_model() -> tuple[Any, Any]:
    """Load the base model with LoRA adapter."""
    global _model, _tokenizer  # noqa: PLW0603

    if _model is not None:
        return _model, _tokenizer

    download_adapter()

    from peft import PeftModel
    from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig

    model_name = MODELS[MODEL_KEY]
    print(f"Loading {model_name}...")

    bnb_config = BitsAndBytesConfig(load_in_4bit=True)

    tokenizer = AutoTokenizer.from_pretrained(model_name)
    model = AutoModelForCausalLM.from_pretrained(
        model_name,
        quantization_config=bnb_config,
        device_map="auto",
    )
    model = PeftModel.from_pretrained(model, ADAPTER_DIR)
    model.eval()

    _model, _tokenizer = model, tokenizer
    return model, tokenizer


# --- RAG ---


def init_retriever():
    """Initialize retriever if ChromaDB index exists."""
    global _retriever  # noqa: PLW0603

    if _retriever is not None:
        return _retriever

    try:
        from codewraith.app.retriever import SpecRetriever

        retriever = SpecRetriever()
        if Path("data/chromadb").exists():
            collection = retriever._get_collection()
            if collection.count() > 0:
                _retriever = retriever
                print(f"RAG retriever loaded ({collection.count()} examples)")
                return _retriever
    except ImportError:
        pass

    return None


def retrieve_context(source_code: str, n_results: int = 3) -> str:
    """Retrieve similar examples as context."""
    retriever = init_retriever()
    if retriever is None:
        return ""

    examples = retriever.retrieve(source_code, n_results=n_results)
    if not examples:
        return ""

    return retriever.format_context(examples)


# --- Inference ---


@spaces.GPU(duration=120)
def generate_spec(
    source_code: str,
    temperature: float = 0.7,
    top_p: float = 0.9,
    max_tokens: int = 2048,
    use_rag: bool = True,
) -> str:
    """Generate a technical specification."""
    if not source_code.strip():
        return "*Please paste some Python source code.*"

    try:
        model, tokenizer = load_model()

        user_content = source_code
        if use_rag:
            context = retrieve_context(source_code)
            if context:
                user_content = context + source_code

        messages = [
            {"role": "system", "content": SYSTEM_MESSAGE},
            {"role": "user", "content": user_content},
        ]

        input_text = tokenizer.apply_chat_template(
            messages, tokenize=False, add_generation_prompt=True
        )
        inputs = tokenizer(input_text, return_tensors="pt").to(model.device)
        input_len = inputs["input_ids"].shape[-1]

        # Retry without RAG if input too long
        if input_len > 6000 and use_rag:
            messages = [
                {"role": "system", "content": SYSTEM_MESSAGE},
                {"role": "user", "content": source_code},
            ]
            input_text = tokenizer.apply_chat_template(
                messages, tokenize=False, add_generation_prompt=True
            )
            inputs = tokenizer(input_text, return_tensors="pt").to(model.device)
            input_len = inputs["input_ids"].shape[-1]

        outputs = model.generate(
            **inputs,
            max_new_tokens=max_tokens,
            temperature=temperature,
            top_p=top_p,
            do_sample=True,
        )

        generated = outputs[0][input_len:]
        spec = tokenizer.decode(generated, skip_special_tokens=True)
        return render_mermaid_images(spec)

    except Exception as e:
        return (
            f"**Error generating specification:**\n\n```\n{e}\n```\n\n"
            "Try with a shorter input or disable RAG."
        )


# --- Gradio UI ---


def render_mermaid_images(spec: str) -> str:
    """Replace mermaid code blocks with rendered SVG images via mermaid.ink.

    Validates the mermaid syntax first, strips malformed blocks, and
    converts valid ones to inline images that render reliably regardless
    of CSS/theme issues.
    """
    import base64
    import re

    valid_starts = (
        "graph ",
        "graph\n",
        "flowchart ",
        "flowchart\n",
        "classDiagram",
        "sequenceDiagram",
        "stateDiagram",
        "erDiagram",
        "gantt",
        "pie",
        "gitgraph",
    )

    def replace_block(match: re.Match) -> str:
        block = match.group(1).strip()
        # Must start with a valid diagram type
        if not any(block.startswith(s) for s in valid_starts):
            return "*[Mermaid diagram removed: unrecognized diagram type]*"
        # Check balanced brackets/braces
        if block.count("[") != block.count("]"):
            return "*[Mermaid diagram removed: unbalanced brackets]*"
        if block.count("{") != block.count("}"):
            return "*[Mermaid diagram removed: unbalanced braces]*"
        if block.count("(") != block.count(")"):
            return "*[Mermaid diagram removed: unbalanced parentheses]*"
        # Encode and return as mermaid.ink image
        encoded = base64.urlsafe_b64encode(block.encode("utf-8")).decode("ascii")
        url = f"https://mermaid.ink/svg/{encoded}"
        return f'<img src="{url}" alt="Dependency Diagram" style="max-width: 600px;">'

    return re.sub(r"```mermaid\s*\n(.*?)```", replace_block, spec, flags=re.DOTALL)


def create_app():
    with gr.Blocks(
        title="CodeWraith - Module-to-Spec Transformer",
    ) as app:
        gr.Markdown(
            "# CodeWraith\n"
            "Generate technical specifications from Python source code.\n\n"
            "Paste your Python code below, adjust sampling parameters, "
            "and click **Generate Specification**."
        )

        code_input = gr.Code(
            language="python",
            label="Python Source Code",
            value=EXAMPLE_CODE,
            lines=15,
        )
        with gr.Row():
            temperature = gr.Slider(0.0, 2.0, value=0.7, step=0.1, label="Temperature")
            top_p = gr.Slider(0.0, 1.0, value=0.9, step=0.05, label="Top-p")
            max_tokens = gr.Slider(256, 8192, value=4096, step=256, label="Max Tokens")
        with gr.Row():
            use_rag = gr.Checkbox(value=True, label="Use RAG (retrieve similar examples)")
            generate_btn = gr.Button("Generate Specification", variant="primary")
            clear_input_btn = gr.Button("Clear Input", variant="secondary")
            clear_output_btn = gr.Button("Clear Output", variant="secondary")

        gr.Markdown("*Model loads on first generation (~30s). Subsequent calls are fast.*")

        spec_output = gr.Markdown(label="Generated Specification")

        loading_msg = "*Generating specification... (loading model if first run)*"
        generate_btn.click(
            fn=lambda: gr.update(value=loading_msg),
            outputs=spec_output,
        ).then(
            fn=generate_spec,
            inputs=[code_input, temperature, top_p, max_tokens, use_rag],
            outputs=spec_output,
        )

        clear_input_btn.click(
            fn=lambda: "",
            outputs=code_input,
        )

        clear_output_btn.click(
            fn=lambda: "",
            outputs=spec_output,
        )

    return app


# Preload adapter on startup (CPU time, free)
print("Preloading adapter...")
download_adapter()
print("Adapter ready. Model will load on first GPU request.")

if __name__ == "__main__":
    app = create_app()
    app.launch()