Spaces:
Runtime error
Runtime error
| import os | |
| import json | |
| import gradio as gr | |
| from llama_cpp import Llama | |
| from radon.complexity import cc_visit | |
| import lizard | |
| # ====================== | |
| # Model Path | |
| # ====================== | |
| MODEL_PATH = "models/deepseek/deepseek-coder-6.7b-instruct.Q4_K_M.gguf" | |
| # ====================== | |
| # Load LLM (runs locally) | |
| # ====================== | |
| llm = Llama( | |
| model_path=MODEL_PATH, | |
| n_ctx=4096, | |
| n_threads=os.cpu_count(), | |
| verbose=False | |
| ) | |
| # ====================== | |
| # Static analysis (fast + reliable) | |
| # ====================== | |
| def static_complexity(code: str): | |
| try: | |
| analysis = lizard.analyze_file.analyze_source_code("code.py", code) | |
| funcs = analysis.function_list | |
| if not funcs: | |
| return "O(1)", "O(1)" | |
| max_cc = max(f.cyclomatic_complexity for f in funcs) | |
| if max_cc <= 2: | |
| return "O(1)", "O(1)" | |
| elif max_cc <= 5: | |
| return "O(n)", "O(1)" | |
| elif max_cc <= 10: | |
| return "O(n^2)", "O(n)" | |
| else: | |
| return "O(n^3)", "O(n)" | |
| except Exception: | |
| return None, None | |
| # ====================== | |
| # LLM fallback | |
| # ====================== | |
| def llm_complexity(code: str): | |
| prompt = f""" | |
| You are an expert algorithm analyst. | |
| Analyze the following Python code. | |
| Rules: | |
| - Output ONLY JSON | |
| - No explanation | |
| Format: | |
| {{ | |
| "time_complexity": "O(?)", | |
| "space_complexity": "O(?)" | |
| }} | |
| Code: | |
| {code} | |
| """ | |
| output = llm( | |
| prompt, | |
| max_tokens=120, | |
| temperature=0.0, | |
| ) | |
| return output["choices"][0]["text"].strip() | |
| # ====================== | |
| # Main predictor | |
| # ====================== | |
| def predict_big_o(code: str): | |
| if not code.strip(): | |
| return '{"time_complexity":"O(1)","space_complexity":"O(1)"}' | |
| time_c, space_c = static_complexity(code) | |
| # if time_c is not None: | |
| # return json.dumps({ | |
| # "time_complexity": time_c, | |
| # "space_complexity": space_c | |
| # }) | |
| return llm_complexity(code) | |
| # ====================== | |
| # Gradio UI | |
| # ====================== | |
| iface = gr.Interface( | |
| fn=predict_big_o, | |
| inputs=gr.Code(language="python", label="Paste your code"), | |
| outputs=gr.Textbox(label="Big-O Prediction"), | |
| title="Big-O Complexity Predictor (Offline)", | |
| description="Predicts Time and Space Complexity locally using DeepSeek GGUF" | |
| ) | |
| if __name__ == "__main__": | |
| iface.launch() | |