import os import gradio as gr from huggingface_hub import InferenceClient hfapi_token=os.getenv('hf_api_token') # ✅ Add your Hugging Face API token here client = InferenceClient("HuggingFaceH4/zephyr-7b-beta", token=hfapi_token) def explain_and_run_code(code_snippet): system_message = "You are an expert assistant that explains Python code snippets clearly,shortly and concisely with the output." explanation = "" output = "" try: messages = [{"role": "system", "content": system_message}] messages.append({ "role": "user", "content": f"Please provide a detailed explanation of the following code snippet:\n```{code_snippet}```" }) for msg in client.chat_completion( messages, max_tokens=2047, stream=True, temperature=0.7, top_p=0.95 ): token = msg["choices"][0]["delta"]["content"] explanation += token except Exception as e: explanation = f"An error occurred during explanation: {str(e)}" try: import io import contextlib output_buffer = io.StringIO() with contextlib.redirect_stdout(output_buffer): exec(code_snippet) output = output_buffer.getvalue() except Exception as e: output = f"An error occurred while running the code: {str(e)}" return f"**Explanation:**\n{explanation}\n\n**Output:**\n{output}" demo = gr.Interface( fn=explain_and_run_code, inputs=gr.Textbox(placeholder="Enter your code snippet here...", label="Code Snippet", lines=10), outputs=gr.Textbox(label="Explanation and Output", lines=15), title="DECIPHER The Python Code Explainer\n\n AI Capstone Project\n (XII-C)", theme="default" ) if __name__ == "__main__": demo.launch()