CoolFace
Apppublic

Sulaiman31/promt_to_code

sourceHugging Faceupdated 11mo agoView on Hugging Face
0likes
app.py82 linesDownload Raw Back to root
1# ==========================2# ๐Ÿš€ CodeToReality โ€” Convert Ideas to Functional Code3# Auto-Fix Version for Hugging Face Spaces4# ==========================5 6import os7import sys8import subprocess9 10# --- Auto-install required packages if missing ---11def install(package_list):12    subprocess.check_call([sys.executable, "-m", "pip", "install", *package_list])13 14try:15    import gradio as gr16    from transformers import pipeline17except ModuleNotFoundError:18    install([19        "gradio==4.37.2",20        "transformers==4.46.1",21        "huggingface_hub==0.26.1",22        "accelerate==0.34.2",23        "torch"24    ])25    import gradio as gr26    from transformers import pipeline27 28 29# --- Load model safely with fallback ---30def load_model():31    try:32        print("๐Ÿ”น Loading StarCoder 2 (1B)โ€ฆ")33        return pipeline("text-generation",34                        model="bigcode/starcoder2-1b",35                        trust_remote_code=True)36    except Exception as e:37        print("โš ๏ธ StarCoder 2 failed:", e)38        print("๐Ÿ”น Falling back to tiny_starcoder_py")39        return pipeline("text-generation",40                        model="bigcode/tiny_starcoder_py",41                        trust_remote_code=True)42 43generator = load_model()44 45 46# --- Main logic ---47def idea_to_code(idea: str, language: str = "Python") -> str:48    """49    Converts a natural-language idea into clean, functional code.50    """51    if not idea.strip():52        return "โŒ Please enter a valid idea first."53 54    prompt = (55        f"### Instruction:\nConvert this idea into functional, efficient {language} code.\n\n"56        f"Idea: {idea}\n\n### Code:\n"57    )58 59    try:60        result = generator(prompt, max_new_tokens=300, temperature=0.2)61        code = result[0]["generated_text"].split("### Code:")[-1].strip()62        return code63    except Exception as e:64        return f"โš ๏ธ Error generating code: {e}"65 66 67# --- Gradio UI ---68iface = gr.Interface(69    fn=idea_to_code,70    inputs=[71        gr.Textbox(label="๐Ÿ’ก Enter Your Idea", placeholder="e.g. A Python script that sends daily motivational quotes."),72        gr.Dropdown(choices=["Python", "JavaScript", "C++", "Java"], label="Select Language", value="Python"),73    ],74    outputs=gr.Code(language="python", label="๐Ÿง  Generated Code"),75    title="๐Ÿง  CodeToReality โ€” Convert Ideas to Functional Code",76    description="Turn your ideas into working code instantly. Powered by StarCoder 2 or its fallback model.",77    theme="gradio/soft",78)79 80if __name__ == "__main__":81    iface.launch()82