import os import gradio as gr from huggingface_hub import InferenceClient # Configuration HF_TOKEN = os.getenv("HF_TOKEN") # Get Hugging Face token from Hugging Face Secrets MODEL_NAME = "microsoft/Phi-3-mini-4k-instruct" # Default model (you can change this if needed) def generate_response(prompt): """Generate response using Hugging Face Inference API""" try: # Initialize InferenceClient with Hugging Face token client = InferenceClient(token=HF_TOKEN) response = client.text_generation( prompt=prompt, temperature=0.7, top_p=0.9, max_new_tokens=800, model=MODEL_NAME ) return response except Exception as e: return f"Error generating response: {str(e)}" def explain_code(code): """Generate explanation for provided code""" if not code.strip(): return "Please enter some code to explain." prompt = f"""<|system|> You are an AI programming tutor. Explain this code in detail: {code} Provide a structured explanation covering: 1. Overall purpose and functionality 2. Key components and their roles 3. Flow of execution 4. Important patterns or techniques used <|end|> <|user|> Please explain this code<|end|> <|assistant|>""" return generate_response(prompt) def create_demo(): """Create Gradio interface""" with gr.Blocks(title="AI Programming Tutor", theme=gr.themes.Soft()) as demo: gr.Markdown(""" # 🤖 AI Programming Tutor Get detailed explanations for your code snippets. """) with gr.Row(): with gr.Column(): code_input = gr.Code( label="Your Code", value="# Enter your code here...", # Default value instead of placeholder language="python", lines=10, interactive=True ) with gr.Row(): submit_btn = gr.Button("Explain Code", variant="primary") clear_btn = gr.Button("Clear") with gr.Column(): explanation_output = gr.Textbox( label="Code Explanation", lines=15, interactive=False ) submit_btn.click( fn=explain_code, inputs=code_input, outputs=explanation_output ) clear_btn.click( fn=lambda: ("# Enter your code here...", ""), # Reset to default value inputs=None, outputs=[code_input, explanation_output] ) return demo # Create and launch the interface demo = create_demo() if __name__ == "__main__": demo.launch()