CoolFace
Apppublic

rawqubit/smart-code-auditor

sourceHugging Faceupdated 6mo agoView on Hugging Face
0likes
app.py69 linesDownload Raw Back to root
1import gradio as gr2from huggingface_hub import InferenceClient3 4# Qwen2.5-Coder is currently the best open-source coding model5try:6    client = InferenceClient("Qwen/Qwen2.5-Coder-32B-Instruct")7except:8    # Fallback if that specific model isn't on free tier right now9    client = InferenceClient("meta-llama/Llama-3.2-3B-Instruct")10 11def analyze_code(code, language, progress=gr.Progress()):12    progress(0.2, desc="Initializing Security Audit...")13    system_prompt = f"""You are a Senior Application Security Engineer and Expert Code Reviewer.14Analyze the following {language} code. 151. Identify any security vulnerabilities (OWASP Top 10, Injection, etc.).162. Point out performance bottlenecks or bad engineering practices.173. Provide a secure, refactored version of the code.18 19Structure your response in Markdown with clear headings for 'Vulnerabilities', 'Best Practices', and 'Refactored Secure Code'.20"""21    messages = [22        {"role": "system", "content": system_prompt},23        {"role": "user", "content": f"```{language}\n{code}\n```"}24    ]25    try:26        progress(0.4, desc="Analyzing codebase and generating report (This takes a few seconds)...")27        response = client.chat_completion(messages, max_tokens=1500)28        progress(1.0, desc="Audit Complete!")29        return response.choices[0].message.content30    except Exception as e:31        return f"⚠️ **Error connecting to Analysis Engine**: {str(e)}"32 33# A sleek Gradio interface34with gr.Blocks(theme=gr.themes.Base()) as demo:35    gr.Markdown("# 🔍 AI Smart Code Auditor")36    gr.Markdown("Secure your application. Paste your code and have an AI Security Engineer audit it for zero-days, vulnerabilities, and bad practices.")37    38    with gr.Row():39        with gr.Column(scale=1):40            lang = gr.Dropdown(choices=["Python", "JavaScript/TypeScript", "C/C++", "Java", "Go", "Rust", "PHP"], value="Python", label="Programming Language")41            code_input = gr.Code(label="Source Code", language="python", lines=15)42            btn = gr.Button("Analyze Code 🚀", variant="primary")43            44            example_code = '''import sqlite345from flask import Flask, request46 47app = Flask(__name__)48 49@app.route('/user')50def get_user():51    username = request.args.get('username')52    conn = sqlite3.connect('users.db')53    cursor = conn.cursor()54    # Vulnerable to SQL Injection55    cursor.execute(f"SELECT * FROM users WHERE username = '{username}'")56    user = cursor.fetchone()57    return str(user)58'''59            gr.Markdown("### Try an example:")60            gr.Examples(examples=[[example_code, "Python"]], inputs=[code_input, lang])61            62        with gr.Column(scale=1):63            output = gr.Markdown(label="Audit Report")64            65    btn.click(analyze_code, inputs=[code_input, lang], outputs=output)66 67if __name__ == "__main__":68    demo.launch(server_name="0.0.0.0")69