CoolFace
Apppublic

JustCode1/code_complexity

sourceHugging Faceapache-2.0updated 7mo agoView on Hugging Face
0likes
app.py110 linesDownload Raw Back to root
1import os
2import json
3import gradio as gr
4from llama_cpp import Llama
5from radon.complexity import cc_visit
6import lizard
7
8# ======================
9# Model Path
10# ======================
11MODEL_PATH = "models/deepseek/deepseek-coder-6.7b-instruct.Q4_K_M.gguf"
12
13# ======================
14# Load LLM (runs locally)
15# ======================
16llm = Llama(
17    model_path=MODEL_PATH,
18    n_ctx=4096,
19    n_threads=os.cpu_count(),
20    verbose=False
21)
22
23# ======================
24# Static analysis (fast + reliable)
25# ======================
26def static_complexity(code: str):
27    try:
28        analysis = lizard.analyze_file.analyze_source_code("code.py", code)
29        funcs = analysis.function_list
30
31        if not funcs:
32            return "O(1)", "O(1)"
33
34        max_cc = max(f.cyclomatic_complexity for f in funcs)
35
36        if max_cc <= 2:
37            return "O(1)", "O(1)"
38        elif max_cc <= 5:
39            return "O(n)", "O(1)"
40        elif max_cc <= 10:
41            return "O(n^2)", "O(n)"
42        else:
43            return "O(n^3)", "O(n)"
44
45    except Exception:
46        return None, None
47
48
49# ======================
50# LLM fallback
51# ======================
52def llm_complexity(code: str):
53    prompt = f"""
54You are an expert algorithm analyst.
55
56Analyze the following Python code.
57
58Rules:
59- Output ONLY JSON
60- No explanation
61
62Format:
63{{
64  "time_complexity": "O(?)",
65  "space_complexity": "O(?)"
66}}
67
68Code:
69{code}
70"""
71
72    output = llm(
73        prompt,
74        max_tokens=120,
75        temperature=0.0,
76    )
77
78    return output["choices"][0]["text"].strip()
79
80
81# ======================
82# Main predictor
83# ======================
84def predict_big_o(code: str):
85    if not code.strip():
86        return '{"time_complexity":"O(1)","space_complexity":"O(1)"}'
87    time_c, space_c = static_complexity(code)
88
89    # if time_c is not None:
90    #     return json.dumps({
91    #         "time_complexity": time_c,
92    #         "space_complexity": space_c
93    #     })
94    return llm_complexity(code)
95
96
97# ======================
98# Gradio UI
99# ======================
100iface = gr.Interface(
101    fn=predict_big_o,
102    inputs=gr.Code(language="python", label="Paste your code"),
103    outputs=gr.Textbox(label="Big-O Prediction"),
104    title="Big-O Complexity Predictor (Offline)",
105    description="Predicts Time and Space Complexity locally using DeepSeek GGUF"
106)
107
108if __name__ == "__main__":
109    iface.launch()
110