Spaces:
Running
Running
Update app.py
Browse files7 unmodified lines89101112131415161718192021222324252627282930313233343536373839404142434445464748491 unmodified line5152535455563 unmodified lines60616263646566676869707172737475767778798012 unmodified lines939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347 unmodified linesfrom huggingface_hub import hf_hub_download# ===== CONFIG =====MODELS_DIR = "/models"CONTEXT_SIZE = 4096MODEL_REPOS = {"Qwen2.5-Coder-7B-Instruct-Q4_K_M.gguf": "bartowski/Qwen2.5-Coder-7B-Instruct-GGUF", # Fixed filename"qwen2.5-coder-3b-instruct-q4_k_m.gguf": "Qwen/Qwen2.5-Coder-3B-Instruct-GGUF","qwen2.5-coder-1.5b-instruct-q4_k_m.gguf": "Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF","qwen2.5-coder-0.5b-instruct-q4_k_m.gguf": "Qwen/Qwen2.5-Coder-0.5B-Instruct-GGUF","DeepSeek-Coder-V2-Lite-Instruct-Q4_K_M.gguf": "bartowski/DeepSeek-Coder-V2-Lite-Instruct-GGUF",}MODELS = {"🧠 DeepSeek V2 Lite (Best)": "DeepSeek-Coder-V2-Lite-Instruct-Q4_K_M.gguf","⚖️ Qwen2.5 Coder 7B (Balanced)": "Qwen2.5-Coder-7B-Instruct-Q4_K_M.gguf", # Fixed filename"🚀 Qwen2.5 Coder 3B (Fast)": "qwen2.5-coder-3b-instruct-q4_k_m.gguf","💨 Qwen2.5 Coder 1.5B (Quick)": "qwen2.5-coder-1.5b-instruct-q4_k_m.gguf","🔬 Qwen2.5 Coder 0.5B (Instant)": "qwen2.5-coder-0.5b-instruct-q4_k_m.gguf",}MODEL_INFO = {"🧠 DeepSeek V2 Lite (Best)": "🏆 MoE 16B • ~9GB • Best quality","⚖️ Qwen2.5 Coder 7B (Balanced)": "⚖️ Balanced • ~4.5GB • Recommended","🚀 Qwen2.5 Coder 3B (Fast)": "🚀 Fast • ~2GB • Great all-rounder","💨 Qwen2.5 Coder 1.5B (Quick)": "💨 Quick • ~1GB • Simple tasks","🔬 Qwen2.5 Coder 0.5B (Instant)": "🔬 Instant • ~0.3GB • Lightning fast",}LANGUAGES = ["Python", "JavaScript", "TypeScript", "Go", "Rust","Java", "C++", "C#", "C", "PHP", "Ruby", "Swift", "Kotlin","Scala", "R", "Julia", "Perl", "HTML/CSS", "SQL", "Bash", "PowerShell", "Lua"]# ===== MODEL CACHE =====loaded_models = {}current_model_name = Nonedef load_model(model_name):global loaded_models, current_model_name1 unmodified lineif model_name == current_model_name and model_name in loaded_models:return loaded_models[model_name]if current_model_name and current_model_name != model_name:if current_model_name in loaded_models:del loaded_models[current_model_name]3 unmodified linesif not filename:return Nonemodel_path = os.path.join(MODELS_DIR, filename)# Auto-download if neededif not os.path.exists(model_path):repo_id = MODEL_REPOS.get(filename)if repo_id:print(f"⬇️ Downloading {filename}...")try:hf_hub_download(repo_id=repo_id, filename=filename, local_dir=MODELS_DIR)print(f"✅ Downloaded {filename}")except Exception as e:print(f"❌ Download failed: {e}")return Noneelse:return Noneprint(f"📥 Loading {model_name}...")try:12 unmodified linesprint(f"❌ Failed to load: {e}")return None# ===== WHISPER =====whisper_model = Nonedef init_whisper():global whisper_modeltry:print("Loading Whisper...")whisper_model = WhisperModel("tiny", device="cpu", compute_type="int8")print("✅ Whisper ready!")except Exception as e:print(f"❌ Whisper failed: {e}")init_whisper()# ===== HELPERS =====def get_status():available = [name for name, file in MODELS.items() if os.path.exists(os.path.join(MODELS_DIR, file))]if current_model_name:short = current_model_name.split('(')[0].strip().split()[-1]return f"🟢 Ready • {len(available)}/{len(MODELS)} cached • Active: {short}"return f"🟡 {len(available)}/{len(MODELS)} models cached"def get_model_info(model_name):return MODEL_INFO.get(model_name, "")def validate_input(text, name="Input"):if not text or not text.strip():return False, f"⚠️ {name} cannot be empty."if len(text) > 50000:return False, f"⚠️ {name} too long."return True, Nonedef transcribe_audio(audio):if not audio:return ""if not whisper_model:return "❌ Whisper unavailable."try:segments, _ = whisper_model.transcribe(audio)return " ".join([s.text for s in segments]).strip() or "⚠️ No speech detected."except Exception as e:return f"❌ {str(e)[:50]}"def generate_response(model_name, prompt, temperature=0.7, max_tokens=2048):llm = load_model(model_name)if not llm:return "❌ **Model not available.** Try selecting a different model."try:if "deepseek" in model_name.lower():formatted = f"### Instruction:\n{prompt}\n\n### Response:\n"stop_tokens = ["### Instruction:", "### Response:"]else:formatted = f"<|im_start|>system\nYou are an expert coding assistant.<|im_end|>\n<|im_start|>user\n{prompt}<|im_end|>\n<|im_start|>assistant\n"stop_tokens = ["<|im_end|>", "<|im_start|>"]output = llm(formatted,max_tokens=max_tokens,temperature=temperature,top_p=0.9,top_k=40,repeat_penalty=1.1,stop=stop_tokens,echo=False)response = output["choices"][0]["text"].strip()return response if response else "⚠️ Empty response."except Exception as e:return f"❌ **Error:** {str(e)[:100]}"def extract_code(text):if not text or "```" not in text:return texttry:parts = text.split("```")if len(parts) >= 2:code = parts[1]if "\n" in code:code = code.split("\n", 1)[-1]return code.strip()except:passreturn text# ===== HISTORY =====def export_chat_history(history):if not history:return None, "⚠️ No chat history to export."filename = f"/tmp/axon_chat_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"with open(filename, "w") as f:json.dump({"exported_at": datetime.now().isoformat(), "messages": history}, f, indent=2)return filename, f"✅ Exported {len(history)} messages!"def export_code(code, language):if not code or not code.strip():return None, "⚠️ No code to export."ext_map = {"Python": "py", "JavaScript": "js", "TypeScript": "ts", "Go": "go", "Rust": "rs", "Java": "java", "C++": "cpp", "C#": "cs", "C": "c", "PHP": "php", "Ruby": "rb", "Swift": "swift", "Kotlin": "kt", "HTML/CSS": "html", "SQL": "sql", "Bash": "sh", "PowerShell": "ps1", "Lua": "lua"}ext = ext_map.get(language, "txt")filename = f"/tmp/axon_code_{datetime.now().strftime('%Y%m%d_%H%M%S')}.{ext}"with open(filename, "w") as f:f.write(code)return filename, f"✅ Exported as .{ext}!"# ===== STREAMING =====def chat_stream(message, history, model_name, temperature, max_tokens):history = history or []valid, error = validate_input(message, "Message")if not valid:history.append({"role": "user", "content": message})history.append({"role": "assistant", "content": error})yield historyreturnllm = load_model(model_name)if not llm:history.append({"role": "user", "content": message})history.append({"role": "assistant", "content": "❌ Model not available."})yield historyreturnif "deepseek" in model_name.lower():conv = "### Instruction:\nYou are an expert coding assistant. Use markdown code blocks.\n\n"for msg in history:conv += f"{'User' if msg['role']=='user' else 'Assistant'}: {msg['content']}\n\n"conv += f"User: {message}\n\n### Response:\n"stop_tokens = ["### Instruction:", "User:"]else:conv = "<|im_start|>system\nYou are an expert coding assistant. Use markdown code blocks.<|im_end|>\n"for msg in history:conv += f"<|im_start|>{msg['role']}\n{msg['content']}<|im_end|>\n"conv += f"<|im_start|>user\n{message}<|im_end|>\n<|im_start|>assistant\n"stop_tokens = ["<|im_end|>", "<|im_start|>"]history.append({"role": "user", "content": message})history.append({"role": "assistant", "content": ""})try:full = ""for chunk in llm(conv, max_tokens=max_tokens, temperature=temperature, top_p=0.9, stop=stop_tokens, stream=True):full += chunk["choices"][0]["text"]history[-1]['content'] = fullyield historyexcept Exception as e:history[-1]['content'] = f"❌ Error: {str(e)[:100]}"yield historydef generate_stream(prompt, language, model_name, temperature, max_tokens):valid, error = validate_input(prompt, "Description")if not valid:yield errorreturnllm = load_model(model_name)if not llm:yield "❌ Model not available."returnif "deepseek" in model_name.lower():formatted = f"### Instruction:\nWrite clean {language} code with comments:\n{prompt}\n\n### Response:\n"stop_tokens = ["### Instruction:"]else:formatted = f"<|im_start|>system\nYou are an expert coder.<|im_end|>\n<|im_start|>user\nWrite clean {language} code with comments:\n{prompt}<|im_end|>\n<|im_start|>assistant\n"stop_tokens = ["<|im_end|>"]try:full = ""for chunk in llm(formatted, max_tokens=max_tokens, temperature=temperature, stop=stop_tokens, stream=True):full += chunk["choices"][0]["text"]yield extract_code(full)except Exception as e:yield f"❌ {str(e)[:50]}"# ===== FEATURES =====def explain_code(code, model_name, detail, max_tokens):valid, err = validate_input(code, "Code")if not valid: return errprompts = {"Brief": f"Explain briefly:\n{code}", "Normal": f"Explain this code:\n{code}", "Detailed": f"Detailed explanation:\n{code}"}return generate_response(model_name, prompts.get(detail, prompts["Normal"]), 0.5, max_tokens)def fix_code(code, error_msg, model_name, max_tokens):valid, err = validate_input(code, "Code")if not valid: return errreturn generate_response(model_name, f"Fix this code. Error: {error_msg or 'Not working'}\n\n{code}", 0.3, max_tokens)def review_code(code, model_name, max_tokens):valid, err = validate_input(code, "Code")if not valid: return errreturn generate_response(model_name, f"Review for bugs, performance, security:\n{code}", 0.4, max_tokens)def convert_code(code, from_lang, to_lang, model_name, max_tokens):valid, err = validate_input(code, "Code")if not valid: return errif from_lang == to_lang: return "⚠️ Same language."result = generate_response(model_name, f"Convert {from_lang} to {to_lang}. Code only:\n{code}", 0.3, max_tokens)return result if result.startswith("❌") else extract_code(result)def generate_tests(code, language, framework, model_name, max_tokens):valid, err = validate_input(code, "Code")if not valid: return errresult = generate_response(model_name, f"Generate {framework or 'pytest'} tests for {language}:\n{code}", 0.3, max_tokens)return result if result.startswith("❌") else extract_code(result)def document_code(code, language, style, model_name, max_tokens):valid, err = validate_input(code, "Code")if not valid: return errresult = generate_response(model_name, f"Add {style.lower()} to this {language} code:\n{code}", 0.4, max_tokens)return result if style == "README" or result.startswith("❌") else extract_code(result)def optimize_code(code, language, focus, model_name, max_tokens):valid, err = validate_input(code, "Code")if not valid: return errreturn generate_response(model_name, f"Optimize {language} for {focus.lower()}. Explain:\n{code}", 0.3, max_tokens)def security_scan(code, model_name, max_tokens):valid, err = validate_input(code, "Code")if not valid: return errreturn generate_response(model_name, f"Security audit. Check for injection, auth issues, data exposure, input validation. For each: Severity, Location, Fix.\n\nCode:\n{code}", 0.3, max_tokens)def analyze_complexity(code, model_name, max_tokens):valid, err = validate_input(code, "Code")if not valid: return errreturn generate_response(model_name, f"Analyze time/space complexity (Big O), bottlenecks, optimizations:\n{code}", 0.4, max_tokens)def build_sql(description, db_type, model_name, max_tokens):valid, err = validate_input(description, "Description")if not valid: return errresult = generate_response(model_name, f"Write {db_type} SQL for:\n{description}", 0.2, max_tokens)return result if result.startswith("❌") else extract_code(result)def build_shell(description, shell_type, model_name, max_tokens):valid, err = validate_input(description, "Description")if not valid: return errresult = generate_response(model_name, f"Write {shell_type} command for:\n{description}", 0.2, max_tokens)return result if result.startswith("❌") else extract_code(result)def code_diff(code1, code2, model_name, max_tokens):v1, e1 = validate_input(code1, "Code 1")v2, e2 = validate_input(code2, "Code 2")if not v1: return e1if not v2: return e2return generate_response(model_name, f"Compare:\n=== CODE 1 ===\n{code1}\n\n=== CODE 2 ===\n{code2}", 0.4, max_tokens)def generate_mock_data(schema, count, format_type, model_name, max_tokens):valid, err = validate_input(schema, "Schema")if not valid: return errresult = generate_response(model_name, f"Generate {count} mock entries as {format_type}:\n{schema}", 0.7, max_tokens)return result if result.startswith("❌") else extract_code(result)def interview_challenge(topic, difficulty, language, model_name, max_tokens):valid, err = validate_input(topic, "Topic")if not valid: return errreturn generate_response(model_name, f"Create {difficulty} {language} interview challenge about {topic}. Include problem, examples, constraints, hints, solution.", 0.6, max_tokens)def to_pseudocode(code, output_type, model_name, max_tokens):valid, err = validate_input(code, "Code")if not valid: return errprompt = f"Convert to pseudocode:\n{code}" if output_type == "Pseudocode" else f"Create Mermaid flowchart:\n{code}"return generate_response(model_name, prompt, 0.3, max_tokens)def build_cron(description, model_name, max_tokens):valid, err = validate_input(description, "Description")if not valid: return errreturn generate_response(model_name, f"Create cron expression for: {description}\nInclude: expression, breakdown, next 5 runs", 0.2, max_tokens)def build_regex(description, model_name, max_tokens):valid, err = validate_input(description, "Description")if not valid: return errreturn generate_response(model_name, f"Create regex for: {description}\nPattern, explanation, examples, Python code:", 0.3, max_tokens)def build_api(description, framework, model_name, max_tokens):valid, err = validate_input(description, "Description")if not valid: return errresult = generate_response(model_name, f"Create {framework} REST endpoint:\n{description}", 0.3, max_tokens)return result if result.startswith("❌") else extract_code(result)def convert_data_format(data, from_fmt, to_fmt, model_name, max_tokens):valid, err = validate_input(data, "Data")if not valid: return errif from_fmt == to_fmt: return "⚠️ Same format."result = generate_response(model_name, f"Convert {from_fmt} to {to_fmt}:\n{data}", 0.1, max_tokens)return result if result.startswith("❌") else extract_code(result)# ===== UI =====with gr.Blocks(title="Axon v6") as demo:gr.HTML("""<div style="background: linear-gradient(135deg, #6366f1, #8b5cf6, #06b6d4); border-radius: 16px; padding: 24px; margin-bottom: 16px;"><h1 style="color: white; margin: 0; font-size: 2rem;">🔥 Axon v6</h1><p style="color: rgba(255,255,255,0.9); margin: 4px 0 0 0;">AI Coding Assistant • 5 Models • 19 Tools • 100% Local</p><div style="display: flex; gap: 8px; margin-top: 12px; flex-wrap: wrap;"><span style="background: rgba(255,255,255,0.2); padding: 4px 12px; border-radius: 20px; font-size: 0.8rem; color: white;">🤖 5 Models</span><span style="background: rgba(255,255,255,0.2); padding: 4px 12px; border-radius: 20px; font-size: 0.8rem; color: white;">🛠️ 19 Tools</span><span style="background: rgba(255,255,255,0.2); padding: 4px 12px; border-radius: 20px; font-size: 0.8rem; color: white;">⚡ llama.cpp</span></div></div>""")status = gr.Markdown(value=get_status, every=5)with gr.Row():model_dropdown = gr.Dropdown(choices=list(MODELS.keys()), value="🚀 Qwen2.5 Coder 3B (Fast)", label="🤖 Model", scale=3)temperature = gr.Slider(0, 1, value=0.7, step=0.1, label="🌡️ Creativity", scale=2)max_tokens = gr.Slider(256, 4096, value=2048, step=256, label="📏 Max Tokens", scale=2)model_info = gr.Markdown(value="🚀 Fast • ~2GB • Great all-rounder")model_dropdown.change(get_model_info, model_dropdown, model_info)with gr.Tabs():with gr.TabItem("🏠 Home"):gr.HTML("""<div style="padding: 20px;"><h2>Welcome to Axon v6! 🔥</h2><p>Free AI coding assistant - 100% local, no API keys.</p><h3>🚀 Quick Start</h3><ol><li>Select a model</li><li>Choose a tool</li><li>Start coding!</li></ol><p><em>Models download automatically on first use</em></p><h3>🤖 Models</h3><table style="width:100%;border-collapse:collapse;"><tr style="background:rgba(99,102,241,0.2);"><th style="padding:8px;text-align:left;">Model</th><th>Size</th><th>Best For</th></tr><tr><td style="padding:8px;">🧠 DeepSeek V2 Lite</td><td>~9GB</td><td>Best quality</td></tr><tr><td style="padding:8px;">⚖️ Qwen2.5 7B</td><td>~4.5GB</td><td>Balanced</td></tr><tr><td style="padding:8px;">🚀 Qwen2.5 3B</td><td>~2GB</td><td>Fast</td></tr><tr><td style="padding:8px;">💨 Qwen2.5 1.5B</td><td>~1GB</td><td>Quick</td></tr><tr><td style="padding:8px;">🔬 Qwen2.5 0.5B</td><td>~0.3GB</td><td>Instant</td></tr></table><h3>📤 Share</h3><div style="display:flex;gap:10px;flex-wrap:wrap;"><a href="https://twitter.com/intent/tweet?text=Check%20out%20Axon%20v6!&url=https://huggingface.co/spaces/AIencoder/Axon" target="_blank" style="background:#1DA1F2;color:white;padding:8px 16px;border-radius:8px;text-decoration:none;">🐦 Twitter</a><a href="https://www.reddit.com/submit?url=https://huggingface.co/spaces/AIencoder/Axon&title=Axon%20v6" target="_blank" style="background:#FF4500;color:white;padding:8px 16px;border-radius:8px;text-decoration:none;">🤖 Reddit</a><a href="https://www.linkedin.com/sharing/share-offsite/?url=https://huggingface.co/spaces/AIencoder/Axon" target="_blank" style="background:#0A66C2;color:white;padding:8px 16px;border-radius:8px;text-decoration:none;">💼 LinkedIn</a></div></div>""")with gr.TabItem("💬 Chat"):chatbot = gr.Chatbot(height=400)with gr.Row():msg = gr.Textbox(placeholder="Ask anything...", show_label=False, scale=8)send = gr.Button("Send", variant="primary", scale=1)with gr.Row():audio = gr.Audio(sources=["microphone"], type="filepath", label="🎤", scale=2)transcribe_btn = gr.Button("🎤", scale=1)clear = gr.Button("🗑️", scale=1)export_chat_btn = gr.Button("💾", scale=1)chat_export_file = gr.File(visible=False)chat_export_status = gr.Markdown("")with gr.TabItem("⚡ Generate"):with gr.Row():with gr.Column():gen_prompt = gr.Textbox(label="📝 Describe", lines=3)gen_lang = gr.Dropdown(LANGUAGES, value="Python", label="Language")gen_btn = gr.Button("⚡ Generate", variant="primary")with gr.Column():gen_output = gr.Code(label="Code", language="python", lines=14)gen_export_btn = gr.Button("💾 Export")gen_export_file = gr.File(visible=False)gen_export_status = gr.Markdown("")with gr.TabItem("🔍 Explain"):with gr.Row():with gr.Column():explain_input = gr.Code(label="Code", lines=10)explain_detail = gr.Radio(["Brief", "Normal", "Detailed"], value="Normal")explain_btn = gr.Button("🔍 Explain", variant="primary")with gr.Column():explain_output = gr.Markdown()with gr.TabItem("🔧 Debug"):with gr.Row():with gr.Column():fix_input = gr.Code(label="Code", lines=8)fix_error = gr.Textbox(label="Error", lines=2)fix_btn = gr.Button("🔧 Fix", variant="primary")with gr.Column():fix_output = gr.Markdown()with gr.TabItem("📋 Review"):with gr.Row():with gr.Column():review_input = gr.Code(label="Code", lines=10)review_btn = gr.Button("📋 Review", variant="primary")with gr.Column():review_output = gr.Markdown()with gr.TabItem("🔐 Security"):with gr.Row():with gr.Column():security_input = gr.Code(label="Code", lines=10)security_btn = gr.Button("🔐 Scan", variant="primary")with gr.Column():security_output = gr.Markdown()with gr.TabItem("📊 Complexity"):with gr.Row():with gr.Column():complexity_input = gr.Code(label="Code", lines=10)complexity_btn = gr.Button("📊 Analyze", variant="primary")with gr.Column():complexity_output = gr.Markdown()with gr.TabItem("🔄 Convert"):with gr.Row():with gr.Column():convert_input = gr.Code(label="Source", lines=10)with gr.Row():convert_from = gr.Dropdown(LANGUAGES, value="Python", label="From")convert_to = gr.Dropdown(LANGUAGES, value="JavaScript", label="To")convert_btn = gr.Button("🔄 Convert", variant="primary")with gr.Column():convert_output = gr.Code(label="Result", lines=10)with gr.TabItem("🧪 Test"):with gr.Row():with gr.Column():test_input = gr.Code(label="Code", lines=10)with gr.Row():test_lang = gr.Dropdown(LANGUAGES[:10], value="Python", label="Language")test_fw = gr.Textbox(label="Framework", placeholder="pytest")test_btn = gr.Button("🧪 Generate", variant="primary")with gr.Column():test_output = gr.Code(label="Tests", lines=10)with gr.TabItem("📝 Document"):with gr.Row():with gr.Column():doc_input = gr.Code(label="Code", lines=10)with gr.Row():doc_lang = gr.Dropdown(LANGUAGES, value="Python", label="Language")doc_style = gr.Dropdown(["Docstrings", "Comments", "Both", "README"], value="Both")doc_btn = gr.Button("📝 Document", variant="primary")with gr.Column():doc_output = gr.Code(label="Documented", lines=10)with gr.TabItem("🚀 Optimize"):with gr.Row():with gr.Column():opt_input = gr.Code(label="Code", lines=10)with gr.Row():opt_lang = gr.Dropdown(LANGUAGES, value="Python", label="Language")opt_focus = gr.Dropdown(["All", "Performance", "Readability", "Memory"], value="All")opt_btn = gr.Button("🚀 Optimize", variant="primary")with gr.Column():opt_output = gr.Markdown()with gr.TabItem("🔀 Diff"):with gr.Row():with gr.Column():diff_code1 = gr.Code(label="Code 1", lines=8)diff_code2 = gr.Code(label="Code 2", lines=8)diff_btn = gr.Button("🔀 Compare", variant="primary")with gr.Column():diff_output = gr.Markdown()with gr.TabItem("📐 Pseudo"):with gr.Row():with gr.Column():pseudo_input = gr.Code(label="Code", lines=10)pseudo_type = gr.Radio(["Pseudocode", "Flowchart"], value="Pseudocode")pseudo_btn = gr.Button("📐 Convert", variant="primary")with gr.Column():pseudo_output = gr.Markdown()with gr.TabItem("🎓 Interview"):with gr.Row():with gr.Column():interview_topic = gr.Textbox(label="Topic", placeholder="Binary trees...")with gr.Row():interview_diff = gr.Dropdown(["Easy", "Medium", "Hard"], value="Medium")interview_lang = gr.Dropdown(LANGUAGES[:8], value="Python")interview_btn = gr.Button("🎓 Generate", variant="primary")with gr.Column():interview_output = gr.Markdown()with gr.TabItem("🛠️ Builders"):gr.Markdown("### 🗄️ SQL")with gr.Row():with gr.Column():sql_desc = gr.Textbox(label="Describe", lines=2)sql_type = gr.Dropdown(["PostgreSQL", "MySQL", "SQLite"], value="PostgreSQL")sql_btn = gr.Button("🗄️ Build", variant="primary")with gr.Column():sql_output = gr.Code(lines=6)gr.Markdown("### 🐚 Shell")with gr.Row():with gr.Column():shell_desc = gr.Textbox(label="Describe", lines=2)shell_type = gr.Dropdown(["Bash", "PowerShell", "Zsh"], value="Bash")shell_btn = gr.Button("🐚 Build", variant="primary")with gr.Column():shell_output = gr.Code(lines=6)gr.Markdown("### ⏰ Cron")with gr.Row():with gr.Column():cron_desc = gr.Textbox(label="Describe", lines=2)cron_btn = gr.Button("⏰ Build", variant="primary")with gr.Column():cron_output = gr.Markdown()gr.Markdown("### 🎯 Regex")with gr.Row():with gr.Column():regex_desc = gr.Textbox(label="Describe", lines=2)regex_btn = gr.Button("🎯 Build", variant="primary")with gr.Column():regex_output = gr.Markdown()gr.Markdown("### 🔗 API")with gr.Row():with gr.Column():api_desc = gr.Textbox(label="Describe", lines=2)api_fw = gr.Dropdown(["FastAPI", "Express", "Flask"], value="FastAPI")api_btn = gr.Button("🔗 Build", variant="primary")with gr.Column():api_output = gr.Code(lines=8)with gr.TabItem("📦 Data"):gr.Markdown("### 📦 Mock Data")with gr.Row():with gr.Column():mock_schema = gr.Textbox(label="Schema", lines=2, placeholder="User: name, email, age...")with gr.Row():mock_count = gr.Slider(1, 20, value=5, step=1, label="Count")mock_format = gr.Dropdown(["JSON", "CSV", "SQL"], value="JSON")mock_btn = gr.Button("📦 Generate", variant="primary")with gr.Column():mock_output = gr.Code(lines=10)gr.Markdown("### 🔄 Format Converter")with gr.Row():with gr.Column():format_input = gr.Code(label="Input", lines=6)with gr.Row():format_from = gr.Dropdown(["JSON", "YAML", "XML", "CSV"], value="JSON")format_to = gr.Dropdown(["JSON", "YAML", "XML", "CSV"], value="YAML")format_btn = gr.Button("🔄 Convert", variant="primary")with gr.Column():format_output = gr.Code(label="Output", lines=6)gr.HTML('<div style="text-align:center;padding:16px;opacity:0.6;">🔥 Axon v6 • <a href="https://huggingface.co/AIencoder">AIencoder</a> • <a href="https://huggingface.co/datasets/AIencoder/llama-cpp-wheels">Wheels</a></div>')# Eventsdef respond(message, history, model, temp, tokens):for updated in chat_stream(message, history, model, temp, tokens):yield updated, ""msg.submit(respond, [msg, chatbot, model_dropdown, temperature, max_tokens], [chatbot, msg])send.click(respond, [msg, chatbot, model_dropdown, temperature, max_tokens], [chatbot, msg])clear.click(lambda: [], None, chatbot)transcribe_btn.click(transcribe_audio, audio, msg)def handle_chat_export(history):file, status = export_chat_history(history)return gr.update(value=file, visible=file is not None), statusdef handle_code_export(code, lang):file, status = export_code(code, lang)return gr.update(value=file, visible=file is not None), statusexport_chat_btn.click(handle_chat_export, chatbot, [chat_export_file, chat_export_status])gen_export_btn.click(handle_code_export, [gen_output, gen_lang], [gen_export_file, gen_export_status])gen_btn.click(generate_stream, [gen_prompt, gen_lang, model_dropdown, temperature, max_tokens], gen_output)explain_btn.click(explain_code, [explain_input, model_dropdown, explain_detail, max_tokens], explain_output)fix_btn.click(fix_code, [fix_input, fix_error, model_dropdown, max_tokens], fix_output)review_btn.click(review_code, [review_input, model_dropdown, max_tokens], review_output)convert_btn.click(convert_code, [convert_input, convert_from, convert_to, model_dropdown, max_tokens], convert_output)test_btn.click(generate_tests, [test_input, test_lang, test_fw, model_dropdown, max_tokens], test_output)doc_btn.click(document_code, [doc_input, doc_lang, doc_style, model_dropdown, max_tokens], doc_output)opt_btn.click(optimize_code, [opt_input, opt_lang, opt_focus, model_dropdown, max_tokens], opt_output)security_btn.click(security_scan, [security_input, model_dropdown, max_tokens], security_output)complexity_btn.click(analyze_complexity, [complexity_input, model_dropdown, max_tokens], complexity_output)diff_btn.click(code_diff, [diff_code1, diff_code2, model_dropdown, max_tokens], diff_output)pseudo_btn.click(to_pseudocode, [pseudo_input, pseudo_type, model_dropdown, max_tokens], pseudo_output)interview_btn.click(interview_challenge, [interview_topic, interview_diff, interview_lang, model_dropdown, max_tokens], interview_output)sql_btn.click(build_sql, [sql_desc, sql_type, model_dropdown, max_tokens], sql_output)shell_btn.click(build_shell, [shell_desc, shell_type, model_dropdown, max_tokens], shell_output)cron_btn.click(build_cron, [cron_desc, model_dropdown, max_tokens], cron_output)regex_btn.click(build_regex, [regex_desc, model_dropdown, max_tokens], regex_output)api_btn.click(build_api, [api_desc, api_fw, model_dropdown, max_tokens], api_output)mock_btn.click(generate_mock_data, [mock_schema, mock_count, mock_format, model_dropdown, max_tokens], mock_output)format_btn.click(convert_data_format, [format_input, format_from, format_to, model_dropdown, max_tokens], format_output)# Pre-download ALL models on startupprint("🔥 Axon v6 starting...")print("⬇️ Pre-downloading all models...")download_results = {}for model_name, filename in MODELS.items():print(f"\n📥 Checking: {model_name}")print(f" Filename: {filename}")model_path = os.path.join(MODELS_DIR, filename)if os.path.exists(model_path):print(f" ✅ Already cached")download_results[model_name] = "cached"else:repo_id = MODEL_REPOS.get(filename)print(f" Repo: {repo_id}")if repo_id:try:print(f" ⬇️ Downloading...")hf_hub_download(repo_id=repo_id, filename=filename, local_dir=MODELS_DIR)print(f" ✅ Downloaded!")download_results[model_name] = "downloaded"except Exception as e:print(f" ❌ FAILED: {e}")download_results[model_name] = f"failed: {e}"else:print(f" ❌ No repo configured!")download_results[model_name] = "no repo"print("\n" + "="*50)print("📊 DOWNLOAD SUMMARY:")for model, status in download_results.items():emoji = "✅" if status in ["cached", "downloaded"] else "❌"print(f" {emoji} {model}: {status}")print("="*50 + "\n")print("🚀 Launching Axon...")demo.launch(server_name="0.0.0.0", server_port=7860, theme=gr.themes.Soft(primary_hue="indigo"))7 unmodified lines89101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778791 unmodified line818283848586873 unmodified lines91929394959697989910012 unmodified lines1131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118127 unmodified linesfrom huggingface_hub import hf_hub_download# ===== CONFIG =====MODELS_DIR = "/data/models"MAX_TOKENS = 2048CONTEXT_SIZE = 4096# Model repos for auto-download (5 models to stay under 50GB)MODEL_REPOS = {"DeepSeek-Coder-V2-Lite-Instruct-Q4_K_M.gguf": "bartowski/DeepSeek-Coder-V2-Lite-Instruct-GGUF","qwen2.5-coder-7b-instruct-q4_k_m.gguf": "Qwen/Qwen2.5-Coder-7B-Instruct-GGUF","qwen2.5-coder-3b-instruct-q4_k_m.gguf": "Qwen/Qwen2.5-Coder-3B-Instruct-GGUF","qwen2.5-coder-1.5b-instruct-q4_k_m.gguf": "Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF","qwen2.5-coder-0.5b-instruct-q4_k_m.gguf": "Qwen/Qwen2.5-Coder-0.5B-Instruct-GGUF",}MODELS = {"🧠 DeepSeek V2 Lite (Best)": "DeepSeek-Coder-V2-Lite-Instruct-Q4_K_M.gguf","⚖️ Qwen2.5 Coder 7B (Balanced)": "qwen2.5-coder-7b-instruct-q4_k_m.gguf","🚀 Qwen2.5 Coder 3B (Fast)": "qwen2.5-coder-3b-instruct-q4_k_m.gguf","💨 Qwen2.5 Coder 1.5B (Quick)": "qwen2.5-coder-1.5b-instruct-q4_k_m.gguf","🔬 Qwen2.5 Coder 0.5B (Instant)": "qwen2.5-coder-0.5b-instruct-q4_k_m.gguf",}LANGUAGES = ["Python", "JavaScript", "TypeScript", "Go", "Rust", "Java", "C++", "C#", "C","PHP", "Ruby", "Swift", "Kotlin", "Scala", "R", "Julia", "Perl", "HTML/CSS","SQL", "Bash", "PowerShell", "Lua"]# ===== GLOBAL STATE =====loaded_models = {}current_model_name = Nonewhisper_model = None# ===== INITIALIZATION =====def init_directories():os.makedirs(MODELS_DIR, exist_ok=True)print(f"📁 Models directory: {MODELS_DIR}")def get_cached_models():if not os.path.exists(MODELS_DIR):return []return [f for f in os.listdir(MODELS_DIR) if f.endswith('.gguf')]def download_model(filename):"""Download a model if not cached"""model_path = os.path.join(MODELS_DIR, filename)if os.path.exists(model_path):return model_pathrepo = MODEL_REPOS.get(filename)if not repo:print(f"❌ No repo found for {filename}")return Noneprint(f"⬇️ Downloading {filename}...")try:path = hf_hub_download(repo_id=repo,filename=filename,local_dir=MODELS_DIR,local_dir_use_symlinks=False)print(f"✅ Downloaded {filename}")return pathexcept Exception as e:print(f"❌ Download failed: {e}")return Nonedef load_model(model_name):global loaded_models, current_model_name1 unmodified lineif model_name == current_model_name and model_name in loaded_models:return loaded_models[model_name]# Unload previous model to save RAMif current_model_name and current_model_name != model_name:if current_model_name in loaded_models:del loaded_models[current_model_name]3 unmodified linesif not filename:return None# Download if neededmodel_path = download_model(filename)if not model_path or not os.path.exists(model_path):return Noneprint(f"📥 Loading {model_name}...")try:12 unmodified linesprint(f"❌ Failed to load: {e}")return Nonedef init_whisper():global whisper_modeltry:print("🎤 Loading Whisper...")whisper_model = WhisperModel("tiny", device="cpu", compute_type="int8")print("✅ Whisper ready!")except Exception as e:print(f"❌ Whisper failed: {e}")# ===== LLM HELPERS =====def generate_response(prompt, model_name, max_tokens=MAX_TOKENS, temperature=0.7):llm = load_model(model_name)if not llm:return "❌ Failed to load model. Please try again."try:response = llm(prompt,max_tokens=max_tokens,temperature=temperature,stop=["<|endoftext|>", "<|im_end|>", "</s>"],echo=False)return response["choices"][0]["text"].strip()except Exception as e:return f"❌ Error: {str(e)}"def generate_stream(prompt, model_name, max_tokens=MAX_TOKENS, temperature=0.7):llm = load_model(model_name)if not llm:yield "❌ Failed to load model. Please try again."returntry:stream = llm(prompt,max_tokens=max_tokens,temperature=temperature,stop=["<|endoftext|>", "<|im_end|>", "</s>"],stream=True,echo=False)for chunk in stream:if "choices" in chunk and chunk["choices"]:text = chunk["choices"][0].get("text", "")if text:yield textexcept Exception as e:yield f"❌ Error: {str(e)}"def format_prompt(system, user):return f"<|im_start|>system\n{system}<|im_end|>\n<|im_start|>user\n{user}<|im_end|>\n<|im_start|>assistant\n"# ===== WHISPER =====def transcribe_audio(audio_path):if not whisper_model or not audio_path:return ""try:segments, _ = whisper_model.transcribe(audio_path, beam_size=1)return " ".join([s.text for s in segments]).strip()except Exception as e:return f"❌ Transcription error: {str(e)}"# ===== TOOL FUNCTIONS =====# --- CORE TOOLS ---def chat_stream(message, history, model, temperature, max_tokens):if not message.strip():yield historyreturnhistory = history or []# Build conversation contextsystem = "You are Axon, an expert AI coding assistant. Be helpful, concise, and provide working code examples when appropriate."conversation = ""for user_msg, assistant_msg in history[-5:]: # Last 5 turnsconversation += f"<|im_start|>user\n{user_msg}<|im_end|>\n<|im_start|>assistant\n{assistant_msg}<|im_end|>\n"prompt = f"<|im_start|>system\n{system}<|im_end|>\n{conversation}<|im_start|>user\n{message}<|im_end|>\n<|im_start|>assistant\n"response = ""history.append([message, ""])for chunk in generate_stream(prompt, model, max_tokens, temperature):response += chunkhistory[-1][1] = responseyield historyyield historydef generate_code(description, language, model, max_tokens):if not description.strip():return "Please provide a description."system = f"You are an expert {language} programmer. Generate clean, well-commented, production-ready code."prompt = format_prompt(system, f"Generate {language} code for: {description}")return generate_response(prompt, model, max_tokens)def explain_code(code, model, detail_level, max_tokens):if not code.strip():return "Please provide code to explain."detail_map = {"Brief": "Give a brief 2-3 sentence explanation.","Normal": "Explain the code clearly with key points.","Detailed": "Provide a comprehensive explanation covering logic, patterns, and potential improvements."}system = "You are an expert code explainer. " + detail_map.get(detail_level, detail_map["Normal"])prompt = format_prompt(system, f"Explain this code:\n\n```\n{code}\n```")return generate_response(prompt, model, max_tokens)def debug_code(code, error, model, max_tokens):if not code.strip():return "Please provide code to debug."system = "You are an expert debugger. Identify bugs, explain the issues, and provide corrected code."user = f"Debug this code:\n\n```\n{code}\n```"if error.strip():user += f"\n\nError message:\n{error}"prompt = format_prompt(system, user)return generate_response(prompt, model, max_tokens)def review_code(code, model, max_tokens):if not code.strip():return "Please provide code to review."system = """You are a senior code reviewer. Review the code for:1. Code quality and readability2. Potential bugs or issues3. Security vulnerabilities4. Performance concerns5. Best practicesProvide specific, actionable feedback."""prompt = format_prompt(system, f"Review this code:\n\n```\n{code}\n```")return generate_response(prompt, model, max_tokens)# --- ADVANCED TOOLS ---def security_scan(code, model, max_tokens):if not code.strip():return "Please provide code to scan."system = """You are a security expert. Scan the code for vulnerabilities including:- SQL injection- XSS (Cross-site scripting)- CSRF vulnerabilities- Insecure data handling- Authentication issues- Input validation problems- Secrets/credentials exposureRate severity (Critical/High/Medium/Low) and provide fixes."""prompt = format_prompt(system, f"Security scan this code:\n\n```\n{code}\n```")return generate_response(prompt, model, max_tokens)def analyze_complexity(code, model, max_tokens):if not code.strip():return "Please provide code to analyze."system = """You are an algorithms expert. Analyze the code complexity:1. Time complexity (Big O notation)2. Space complexity (Big O notation)3. Explain the analysis step by step4. Suggest optimizations if possible"""prompt = format_prompt(system, f"Analyze complexity:\n\n```\n{code}\n```")return generate_response(prompt, model, max_tokens)def convert_code(code, from_lang, to_lang, model, max_tokens):if not code.strip():return "Please provide code to convert."system = f"You are an expert polyglot programmer. Convert code from {from_lang} to {to_lang}. Preserve functionality and use idiomatic patterns for the target language."prompt = format_prompt(system, f"Convert this {from_lang} code to {to_lang}:\n\n```\n{code}\n```")return generate_response(prompt, model, max_tokens)def generate_tests(code, language, framework, model, max_tokens):if not code.strip():return "Please provide code to test."system = f"You are a testing expert. Generate comprehensive {framework} unit tests for {language} code. Include edge cases, error cases, and happy path tests."prompt = format_prompt(system, f"Generate {framework} tests for:\n\n```\n{code}\n```")return generate_response(prompt, model, max_tokens)def document_code(code, language, style, model, max_tokens):if not code.strip():return "Please provide code to document."style_map = {"Docstrings": "Add comprehensive docstrings to all functions/classes.","Inline Comments": "Add helpful inline comments explaining the logic.","Both": "Add both docstrings and inline comments."}system = f"You are a documentation expert. {style_map.get(style, style_map['Both'])} Use {language} documentation conventions."prompt = format_prompt(system, f"Document this code:\n\n```\n{code}\n```")return generate_response(prompt, model, max_tokens)def optimize_code(code, language, focus, model, max_tokens):if not code.strip():return "Please provide code to optimize."system = f"You are a performance optimization expert. Optimize the {language} code focusing on {focus}. Show the optimized code and explain the improvements."prompt = format_prompt(system, f"Optimize this code for {focus}:\n\n```\n{code}\n```")return generate_response(prompt, model, max_tokens)def code_diff(code1, code2, model, max_tokens):if not code1.strip() or not code2.strip():return "Please provide both code snippets to compare."system = "You are a code analysis expert. Compare the two code snippets and explain the differences, which is better, and why."prompt = format_prompt(system, f"Compare these code snippets:\n\n**Code 1:**\n```\n{code1}\n```\n\n**Code 2:**\n```\n{code2}\n```")return generate_response(prompt, model, max_tokens)def to_pseudocode(code, output_type, model, max_tokens):if not code.strip():return "Please provide code to convert."if output_type == "Pseudocode":system = "Convert the code to clear, readable pseudocode that anyone can understand."else:system = "Convert the code to a text-based flowchart using ASCII art or a structured description."prompt = format_prompt(system, f"Convert to {output_type}:\n\n```\n{code}\n```")return generate_response(prompt, model, max_tokens)def interview_challenge(topic, difficulty, language, model, max_tokens):system = f"You are a technical interviewer. Create a {difficulty} {language} coding challenge about {topic}. Include: problem statement, examples, constraints, hints, and a solution with explanation."prompt = format_prompt(system, f"Create a {difficulty} {topic} challenge in {language}")return generate_response(prompt, model, max_tokens)# --- BUILDERS ---def build_sql(description, sql_type, model, max_tokens):if not description.strip():return "Please describe what SQL you need."system = f"You are a SQL expert. Generate {sql_type} SQL queries. Include comments explaining the query."prompt = format_prompt(system, f"Generate SQL for: {description}")return generate_response(prompt, model, max_tokens)def build_shell(description, shell_type, model, max_tokens):if not description.strip():return "Please describe what command you need."system = f"You are a {shell_type} expert. Generate safe, well-commented shell commands. Warn about any dangerous operations."prompt = format_prompt(system, f"Generate {shell_type} command for: {description}")return generate_response(prompt, model, max_tokens)def build_cron(description, model, max_tokens):if not description.strip():return "Please describe the schedule you need."system = "You are a cron expert. Generate cron expressions with clear explanations. Include the cron format: minute hour day month weekday"prompt = format_prompt(system, f"Generate cron expression for: {description}")return generate_response(prompt, model, max_tokens)def build_regex(description, model, max_tokens):if not description.strip():return "Please describe the pattern you need."system = "You are a regex expert. Generate regular expressions with explanations and test examples. Support multiple regex flavors if relevant."prompt = format_prompt(system, f"Generate regex for: {description}")return generate_response(prompt, model, max_tokens)def build_api(description, framework, model, max_tokens):if not description.strip():return "Please describe the API endpoint you need."system = f"You are an API expert. Generate a complete {framework} REST API endpoint with error handling, validation, and documentation."prompt = format_prompt(system, f"Generate {framework} API endpoint for: {description}")return generate_response(prompt, model, max_tokens)# --- DATA TOOLS ---def generate_mock_data(schema, count, format_type, model, max_tokens):if not schema.strip():return "Please provide a schema or description."system = f"You are a data generation expert. Generate {count} realistic mock data records in {format_type} format based on the schema."prompt = format_prompt(system, f"Generate {count} mock records in {format_type}:\n\nSchema: {schema}")return generate_response(prompt, model, max_tokens)def convert_data_format(data, from_format, to_format, model, max_tokens):if not data.strip():return "Please provide data to convert."system = f"Convert the data from {from_format} to {to_format}. Preserve all information and use proper formatting."prompt = format_prompt(system, f"Convert from {from_format} to {to_format}:\n\n```\n{data}\n```")return generate_response(prompt, model, max_tokens)# --- NEW v26 TOOLS ---def refactor_code(code, language, pattern, model, max_tokens):if not code.strip():return "Please provide code to refactor."system = f"You are a software architect. Refactor the {language} code using {pattern} patterns. Explain the improvements and show before/after."prompt = format_prompt(system, f"Refactor using {pattern}:\n\n```\n{code}\n```")return generate_response(prompt, model, max_tokens)def generate_benchmark(code, language, model, max_tokens):if not code.strip():return "Please provide code to benchmark."system = f"You are a performance testing expert. Generate comprehensive {language} benchmark code to measure performance. Include setup, warmup, multiple iterations, and statistics."prompt = format_prompt(system, f"Generate benchmark for:\n\n```\n{code}\n```")return generate_response(prompt, model, max_tokens)def analyze_dependencies(code, language, model, max_tokens):if not code.strip():return "Please provide code to analyze."system = f"You are a dependency analysis expert. Analyze the {language} code for:1. Direct imports/dependencies2. Potential circular dependencies3. Unused imports4. Missing dependencies5. Version compatibility concerns6. Security advisories for known packages"prompt = format_prompt(system, f"Analyze dependencies:\n\n```\n{code}\n```")return generate_response(prompt, model, max_tokens)def generate_changelog(diff_or_commits, version, model, max_tokens):if not diff_or_commits.strip():return "Please provide diff or commit messages."system = """You are a technical writer. Generate a professional changelog entry with:- Version number and date- Categories: Added, Changed, Fixed, Removed, Security- Clear, user-friendly descriptions- Breaking changes highlighted"""prompt = format_prompt(system, f"Generate changelog for version {version}:\n\n{diff_or_commits}")return generate_response(prompt, model, max_tokens)def suggest_improvements(code, language, model, max_tokens):if not code.strip():return "Please provide code to analyze."system = f"""You are a senior {language} developer. Provide actionable improvement suggestions:1. Code quality improvements2. Performance optimizations3. Better error handling4. Modern language features to use5. Design pattern recommendations6. Testing suggestionsRate each suggestion by impact (High/Medium/Low) and effort."""prompt = format_prompt(system, f"Suggest improvements:\n\n```\n{code}\n```")return generate_response(prompt, model, max_tokens)# ===== UI =====def create_ui():# Check cached modelscached = get_cached_models()total_models = len(MODELS)css = """.main-header { text-align: center; margin-bottom: 20px; }.tool-description { color: #666; font-size: 0.9em; margin-bottom: 10px; }.status-bar { padding: 10px; border-radius: 8px; margin-bottom: 15px; }"""with gr.Blocks(title="Axon v26", css=css) as demo:# Headergr.HTML("""<div class="main-header"><h1>⚡ Axon v26</h1><p>The Ultimate Free AI Coding Assistant • 5 Models • 25 Tools • 100% Local</p></div>""")# Status barstatus_emoji = "🟢" if cached else "🟡"gr.HTML(f"""<div class="status-bar" style="background: linear-gradient(135deg, #667eea22, #764ba222);">{status_emoji} <strong>{len(cached)}/{total_models}</strong> models cached •Models download on first use (~1-9GB each)</div>""")# Global controlswith gr.Row():model_dropdown = gr.Dropdown(choices=list(MODELS.keys()),value=list(MODELS.keys())[2], # Default to 3Blabel="🤖 Model",scale=2)max_tokens = gr.Slider(256, 4096, value=2048, step=256, label="Max Tokens", scale=1)# Tabswith gr.Tabs():# === CHAT TAB ===with gr.Tab("💬 Chat"):gr.HTML("<p class='tool-description'>Have a conversation about code, get help, ask questions.</p>")chatbot = gr.Chatbot(height=400)with gr.Row():msg = gr.Textbox(placeholder="Ask me anything about code...", scale=4, show_label=False)send_btn = gr.Button("Send", variant="primary")with gr.Row():temperature = gr.Slider(0, 1, value=0.7, step=0.1, label="Temperature")audio_input = gr.Audio(type="filepath", label="🎤 Voice Input")transcribe_btn = gr.Button("Transcribe")clear_btn = gr.Button("Clear Chat")# === GENERATE TAB ===with gr.Tab("⚡ Generate"):gr.HTML("<p class='tool-description'>Describe what you want, get working code.</p>")gen_prompt = gr.Textbox(lines=3, placeholder="Describe the code you want...", label="Description")gen_lang = gr.Dropdown(choices=LANGUAGES, value="Python", label="Language")gen_btn = gr.Button("Generate", variant="primary")gen_output = gr.Code(label="Generated Code", language="python")# === EXPLAIN TAB ===with gr.Tab("🔍 Explain"):gr.HTML("<p class='tool-description'>Understand any code with detailed explanations.</p>")explain_input = gr.Code(lines=10, label="Code to Explain", language="python")explain_detail = gr.Radio(["Brief", "Normal", "Detailed"], value="Normal", label="Detail Level")explain_btn = gr.Button("Explain", variant="primary")explain_output = gr.Markdown(label="Explanation")# === DEBUG TAB ===with gr.Tab("🔧 Debug"):gr.HTML("<p class='tool-description'>Find and fix bugs with AI assistance.</p>")debug_input = gr.Code(lines=10, label="Buggy Code", language="python")debug_error = gr.Textbox(lines=3, placeholder="Paste error message (optional)", label="Error Message")debug_btn = gr.Button("Debug", variant="primary")debug_output = gr.Markdown(label="Debug Results")# === REVIEW TAB ===with gr.Tab("📋 Review"):gr.HTML("<p class='tool-description'>Get comprehensive code review feedback.</p>")review_input = gr.Code(lines=10, label="Code to Review", language="python")review_btn = gr.Button("Review", variant="primary")review_output = gr.Markdown(label="Review Results")# === SECURITY TAB ===with gr.Tab("🔐 Security"):gr.HTML("<p class='tool-description'>Scan code for security vulnerabilities.</p>")security_input = gr.Code(lines=10, label="Code to Scan", language="python")security_btn = gr.Button("Scan", variant="primary")security_output = gr.Markdown(label="Security Report")# === COMPLEXITY TAB ===with gr.Tab("📊 Complexity"):gr.HTML("<p class='tool-description'>Analyze time and space complexity (Big O).</p>")complexity_input = gr.Code(lines=10, label="Code to Analyze", language="python")complexity_btn = gr.Button("Analyze", variant="primary")complexity_output = gr.Markdown(label="Complexity Analysis")# === CONVERT TAB ===with gr.Tab("🔄 Convert"):gr.HTML("<p class='tool-description'>Translate code between programming languages.</p>")convert_input = gr.Code(lines=10, label="Code to Convert", language="python")with gr.Row():convert_from = gr.Dropdown(choices=LANGUAGES, value="Python", label="From")convert_to = gr.Dropdown(choices=LANGUAGES, value="JavaScript", label="To")convert_btn = gr.Button("Convert", variant="primary")convert_output = gr.Code(label="Converted Code", language="javascript")# === TEST TAB ===with gr.Tab("🧪 Test"):gr.HTML("<p class='tool-description'>Generate comprehensive unit tests.</p>")test_input = gr.Code(lines=10, label="Code to Test", language="python")with gr.Row():test_lang = gr.Dropdown(choices=LANGUAGES, value="Python", label="Language")test_fw = gr.Dropdown(choices=["pytest", "unittest", "Jest", "Mocha", "JUnit", "RSpec"], value="pytest", label="Framework")test_btn = gr.Button("Generate Tests", variant="primary")test_output = gr.Code(label="Generated Tests", language="python")# === DOCUMENT TAB ===with gr.Tab("📝 Document"):gr.HTML("<p class='tool-description'>Add documentation to your code.</p>")doc_input = gr.Code(lines=10, label="Code to Document", language="python")with gr.Row():doc_lang = gr.Dropdown(choices=LANGUAGES, value="Python", label="Language")doc_style = gr.Dropdown(choices=["Docstrings", "Inline Comments", "Both"], value="Both", label="Style")doc_btn = gr.Button("Document", variant="primary")doc_output = gr.Code(label="Documented Code", language="python")# === OPTIMIZE TAB ===with gr.Tab("🚀 Optimize"):gr.HTML("<p class='tool-description'>Improve code performance.</p>")opt_input = gr.Code(lines=10, label="Code to Optimize", language="python")with gr.Row():opt_lang = gr.Dropdown(choices=LANGUAGES, value="Python", label="Language")opt_focus = gr.Dropdown(choices=["Speed", "Memory", "Readability", "All"], value="All", label="Focus")opt_btn = gr.Button("Optimize", variant="primary")opt_output = gr.Markdown(label="Optimized Code")# === DIFF TAB ===with gr.Tab("🔀 Diff"):gr.HTML("<p class='tool-description'>Compare two code snippets.</p>")with gr.Row():diff_code1 = gr.Code(lines=8, label="Code 1", language="python")diff_code2 = gr.Code(lines=8, label="Code 2", language="python")diff_btn = gr.Button("Compare", variant="primary")diff_output = gr.Markdown(label="Comparison")# === PSEUDOCODE TAB ===with gr.Tab("📐 Pseudo"):gr.HTML("<p class='tool-description'>Convert code to pseudocode or flowcharts.</p>")pseudo_input = gr.Code(lines=10, label="Code", language="python")pseudo_type = gr.Radio(["Pseudocode", "Flowchart"], value="Pseudocode", label="Output Type")pseudo_btn = gr.Button("Convert", variant="primary")pseudo_output = gr.Markdown(label="Output")# === INTERVIEW TAB ===with gr.Tab("🎓 Interview"):gr.HTML("<p class='tool-description'>Generate coding interview challenges.</p>")with gr.Row():interview_topic = gr.Textbox(placeholder="e.g., binary trees, dynamic programming", label="Topic")interview_diff = gr.Dropdown(choices=["Easy", "Medium", "Hard"], value="Medium", label="Difficulty")interview_lang = gr.Dropdown(choices=LANGUAGES, value="Python", label="Language")interview_btn = gr.Button("Generate Challenge", variant="primary")interview_output = gr.Markdown(label="Challenge")# === SQL TAB ===with gr.Tab("🗄️ SQL"):gr.HTML("<p class='tool-description'>Generate SQL queries from natural language.</p>")sql_desc = gr.Textbox(lines=3, placeholder="Describe your query...", label="Description")sql_type = gr.Dropdown(choices=["MySQL", "PostgreSQL", "SQLite", "SQL Server", "Oracle"], value="PostgreSQL", label="Database")sql_btn = gr.Button("Generate SQL", variant="primary")sql_output = gr.Code(label="Generated SQL", language="sql")# === SHELL TAB ===with gr.Tab("🐚 Shell"):gr.HTML("<p class='tool-description'>Generate shell commands from descriptions.</p>")shell_desc = gr.Textbox(lines=3, placeholder="Describe what you want to do...", label="Description")shell_type = gr.Dropdown(choices=["Bash", "PowerShell", "Zsh", "Fish"], value="Bash", label="Shell")shell_btn = gr.Button("Generate", variant="primary")shell_output = gr.Code(label="Generated Command", language="bash")# === CRON TAB ===with gr.Tab("⏰ Cron"):gr.HTML("<p class='tool-description'>Generate cron schedule expressions.</p>")cron_desc = gr.Textbox(lines=2, placeholder="e.g., Every Monday at 9am", label="Schedule Description")cron_btn = gr.Button("Generate", variant="primary")cron_output = gr.Markdown(label="Cron Expression")# === REGEX TAB ===with gr.Tab("🎯 Regex"):gr.HTML("<p class='tool-description'>Generate regular expressions with explanations.</p>")regex_desc = gr.Textbox(lines=2, placeholder="e.g., Match email addresses", label="Pattern Description")regex_btn = gr.Button("Generate", variant="primary")regex_output = gr.Markdown(label="Regex Pattern")# === API TAB ===with gr.Tab("🔗 API"):gr.HTML("<p class='tool-description'>Generate REST API endpoint boilerplate.</p>")api_desc = gr.Textbox(lines=3, placeholder="Describe your API endpoint...", label="Description")api_fw = gr.Dropdown(choices=["FastAPI", "Flask", "Express", "Django", "Spring Boot", "Go Gin"], value="FastAPI", label="Framework")api_btn = gr.Button("Generate", variant="primary")api_output = gr.Code(label="Generated API", language="python")# === MOCK DATA TAB ===with gr.Tab("📦 Mock"):gr.HTML("<p class='tool-description'>Generate realistic test data.</p>")mock_schema = gr.Textbox(lines=3, placeholder="e.g., users with name, email, age", label="Schema Description")with gr.Row():mock_count = gr.Number(value=5, label="Count", precision=0)mock_format = gr.Dropdown(choices=["JSON", "CSV", "SQL INSERT", "YAML"], value="JSON", label="Format")mock_btn = gr.Button("Generate", variant="primary")mock_output = gr.Code(label="Generated Data", language="json")# === FORMAT TAB ===with gr.Tab("🔄 Format"):gr.HTML("<p class='tool-description'>Convert between data formats.</p>")format_input = gr.Code(lines=10, label="Input Data", language="json")with gr.Row():format_from = gr.Dropdown(choices=["JSON", "YAML", "XML", "CSV", "TOML"], value="JSON", label="From")format_to = gr.Dropdown(choices=["JSON", "YAML", "XML", "CSV", "TOML"], value="YAML", label="To")format_btn = gr.Button("Convert", variant="primary")format_output = gr.Code(label="Converted Data", language="yaml")# === REFACTOR TAB (NEW) ===with gr.Tab("🎨 Refactor"):gr.HTML("<p class='tool-description'>Restructure code using design patterns.</p>")refactor_input = gr.Code(lines=10, label="Code to Refactor", language="python")with gr.Row():refactor_lang = gr.Dropdown(choices=LANGUAGES, value="Python", label="Language")refactor_pattern = gr.Dropdown(choices=["Clean Code", "SOLID", "DRY", "Factory", "Singleton", "Observer", "Strategy"], value="Clean Code", label="Pattern")refactor_btn = gr.Button("Refactor", variant="primary")refactor_output = gr.Markdown(label="Refactored Code")# === BENCHMARK TAB (NEW) ===with gr.Tab("📊 Bench"):gr.HTML("<p class='tool-description'>Generate performance benchmark code.</p>")bench_input = gr.Code(lines=10, label="Code to Benchmark", language="python")bench_lang = gr.Dropdown(choices=LANGUAGES, value="Python", label="Language")bench_btn = gr.Button("Generate Benchmark", variant="primary")bench_output = gr.Code(label="Benchmark Code", language="python")# === DEPENDENCIES TAB (NEW) ===with gr.Tab("🔗 Deps"):gr.HTML("<p class='tool-description'>Analyze imports and dependencies.</p>")deps_input = gr.Code(lines=10, label="Code to Analyze", language="python")deps_lang = gr.Dropdown(choices=LANGUAGES, value="Python", label="Language")deps_btn = gr.Button("Analyze", variant="primary")deps_output = gr.Markdown(label="Dependency Analysis")# === CHANGELOG TAB (NEW) ===with gr.Tab("📋 Change"):gr.HTML("<p class='tool-description'>Generate changelogs from diffs or commits.</p>")changelog_input = gr.Textbox(lines=10, placeholder="Paste git diff, commit messages, or describe changes...", label="Changes")changelog_version = gr.Textbox(value="1.0.0", label="Version")changelog_btn = gr.Button("Generate Changelog", variant="primary")changelog_output = gr.Markdown(label="Changelog")# === SUGGEST TAB (NEW) ===with gr.Tab("💡 Suggest"):gr.HTML("<p class='tool-description'>Get AI-powered improvement suggestions.</p>")suggest_input = gr.Code(lines=10, label="Code to Analyze", language="python")suggest_lang = gr.Dropdown(choices=LANGUAGES, value="Python", label="Language")suggest_btn = gr.Button("Get Suggestions", variant="primary")suggest_output = gr.Markdown(label="Suggestions")# Footergr.HTML("""<div style="text-align: center; margin-top: 20px; padding: 15px; background: linear-gradient(135deg, #667eea11, #764ba211); border-radius: 10px;"><p><strong>⚡ Axon v26</strong> • Built with ❤️ by <a href="https://huggingface.co/AIencoder" target="_blank">AIencoder</a></p><p style="font-size: 0.85em; color: #666;"><a href="https://huggingface.co/datasets/AIencoder/llama-cpp-wheels" target="_blank">🛞 Pre-built Wheels</a> •100% Local • No API Keys • MIT License</p></div>""")# === EVENT HANDLERS ===# Chatdef respond(message, history, model, temp, tokens):history = history or []for updated_history in chat_stream(message, history, model, temp, tokens):yield updated_history, ""msg.submit(respond, [msg, chatbot, model_dropdown, temperature, max_tokens], [chatbot, msg])send_btn.click(respond, [msg, chatbot, model_dropdown, temperature, max_tokens], [chatbot, msg])clear_btn.click(lambda: [], None, chatbot)transcribe_btn.click(transcribe_audio, audio_input, msg)# Core toolsgen_btn.click(generate_code, [gen_prompt, gen_lang, model_dropdown, max_tokens], gen_output)explain_btn.click(explain_code, [explain_input, model_dropdown, explain_detail, max_tokens], explain_output)debug_btn.click(debug_code, [debug_input, debug_error, model_dropdown, max_tokens], debug_output)review_btn.click(review_code, [review_input, model_dropdown, max_tokens], review_output)# Advanced toolssecurity_btn.click(security_scan, [security_input, model_dropdown, max_tokens], security_output)complexity_btn.click(analyze_complexity, [complexity_input, model_dropdown, max_tokens], complexity_output)convert_btn.click(convert_code, [convert_input, convert_from, convert_to, model_dropdown, max_tokens], convert_output)test_btn.click(generate_tests, [test_input, test_lang, test_fw, model_dropdown, max_tokens], test_output)doc_btn.click(document_code, [doc_input, doc_lang, doc_style, model_dropdown, max_tokens], doc_output)opt_btn.click(optimize_code, [opt_input, opt_lang, opt_focus, model_dropdown, max_tokens], opt_output)diff_btn.click(code_diff, [diff_code1, diff_code2, model_dropdown, max_tokens], diff_output)pseudo_btn.click(to_pseudocode, [pseudo_input, pseudo_type, model_dropdown, max_tokens], pseudo_output)interview_btn.click(interview_challenge, [interview_topic, interview_diff, interview_lang, model_dropdown, max_tokens], interview_output)# Builderssql_btn.click(build_sql, [sql_desc, sql_type, model_dropdown, max_tokens], sql_output)shell_btn.click(build_shell, [shell_desc, shell_type, model_dropdown, max_tokens], shell_output)cron_btn.click(build_cron, [cron_desc, model_dropdown, max_tokens], cron_output)regex_btn.click(build_regex, [regex_desc, model_dropdown, max_tokens], regex_output)api_btn.click(build_api, [api_desc, api_fw, model_dropdown, max_tokens], api_output)# Data toolsmock_btn.click(generate_mock_data, [mock_schema, mock_count, mock_format, model_dropdown, max_tokens], mock_output)format_btn.click(convert_data_format, [format_input, format_from, format_to, model_dropdown, max_tokens], format_output)# NEW v26 toolsrefactor_btn.click(refactor_code, [refactor_input, refactor_lang, refactor_pattern, model_dropdown, max_tokens], refactor_output)bench_btn.click(generate_benchmark, [bench_input, bench_lang, model_dropdown, max_tokens], bench_output)deps_btn.click(analyze_dependencies, [deps_input, deps_lang, model_dropdown, max_tokens], deps_output)changelog_btn.click(generate_changelog, [changelog_input, changelog_version, model_dropdown, max_tokens], changelog_output)suggest_btn.click(suggest_improvements, [suggest_input, suggest_lang, model_dropdown, max_tokens], suggest_output)return demo# ===== MAIN =====if __name__ == "__main__":print("⚡ Axon v26 - The FINAL Version")print("=" * 40)init_directories()init_whisper()cached = get_cached_models()print(f"📦 Cached models: {len(cached)}/{len(MODELS)}")for m in cached:print(f" ✅ {m}")print("\n🚀 Starting Axon...")demo = create_ui()demo.launch(server_name="0.0.0.0", server_port=7860)
app.py+686-608