File size: 1,879 Bytes
c7b4ddf
42192c3
eef3de2
c7b4ddf
c8848c3
c7b4ddf
eef3de2
206de0c
b15554e
206de0c
 
 
c3df842
0fe7900
 
 
c8848c3
0fe7900
 
c3df842
 
0fe7900
c3df842
0fe7900
 
c3df842
4ff9e29
206de0c
 
 
 
 
 
 
 
 
 
 
c3df842
206de0c
eef3de2
206de0c
eef3de2
c8848c3
c3df842
206de0c
0fe7900
206de0c
c8848c3
0fe7900
42192c3
 
eef3de2
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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()