rishika18/code-explainer
0
1# app.py2# -*- coding: utf-8 -*-3 4import gradio as gr5import google.generativeai as palm6print("google-generativeai version:", palm.__version__)7import os8os.environ["HF_HOME"] = "/tmp/hf_cache" 9 10# -------------------------11# CONFIGURE PaLM API12# -------------------------13# Replace with your actual PaLM API key14API_KEY = "AIzaSyDa89CpRmIwKA6h8fBO533Si0xK_YvSs7I"15palm.configure(api_key=API_KEY)16 17# -------------------------18# FIXED WORKING MODEL19# -------------------------20model = "models/text-bison-001"21 22# -------------------------23# DEFINE COMPLETION FUNCTION24# -------------------------25def get_completion(code_snippet: str) -> str:26 """27 Generates a real step-by-step explanation for the given code snippet28 using PaLM API (generate_text). Handles errors gracefully.29 """30 if not code_snippet.strip():31 return "Please enter a code snippet."32 33 prompt = f"""34You are a Python Code Explainer.35Explain the following Python code step-by-step, showing intermediate results if possible.36 37Code to explain:38{code_snippet}39"""40 41 try:42 completion = palm.generate_text(43 model=model,44 prompt=prompt,45 temperature=0,46 max_output_tokens=100047 )48 explanation = completion.result49 if not explanation or explanation.strip() == "":50 return "The model did not return any explanation."51 return explanation52 except Exception as e:53 return f"Error generating explanation: {str(e)}"54 55# -------------------------56# DEFINE GRADIO INTERFACE57# -------------------------58iface = gr.Interface(59 fn=get_completion,60 inputs=[gr.Textbox(label="Insert Code Snippet", lines=5)],61 outputs=[gr.Textbox(label="Explanation Here", lines=12)],62 title="Code Explainer",63 description="Paste any Python code snippet and get a step-by-step explanation."64)65 66# -------------------------67# LAUNCH APP68# -------------------------69if __name__ == "__main__":70 iface.launch()71 