Spaces:
Runtime error
Runtime error
Download app.py from umarfarooqtoru/codeexplainer: direct link, hf CLI and curl.
- Browser
- Download file 1.7 kB
-
https://huggingface.co/spaces/umarfarooqtoru/codeexplainer/resolve/aa6ef3bf7d5e00416bfec4be4fadb1fb5d7b50b2/app.py
- Command line
-
hf download hf://spaces/umarfarooqtoru/codeexplainer@aa6ef3bf7d5e00416bfec4be4fadb1fb5d7b50b2/app.py
-
curl -L -o app.py https://huggingface.co/spaces/umarfarooqtoru/codeexplainer/resolve/aa6ef3bf7d5e00416bfec4be4fadb1fb5d7b50b2/app.py
1.7 kB
| import gradio as gr | |
| import google.generativeai as genai | |
| import os | |
| from huggingface_hub import login | |
| # Use your Hugging Face variable for the Gemini API key | |
| GEMINI_API_KEY = os.getenv("GOOGLEAPI", "PASTE_YOUR_GEMINI_API_KEY_HERE") | |
| genai.configure(api_key=GEMINI_API_KEY) | |
| def explain_code(files, _): | |
| model = genai.GenerativeModel("gemini-pro") | |
| explanations = [] | |
| for file in files: | |
| filename = file.name if hasattr(file, 'name') else 'Uploaded File' | |
| if isinstance(file, bytes): | |
| code = file.decode('utf-8') | |
| elif hasattr(file, 'read'): | |
| code = file.read().decode('utf-8') | |
| else: | |
| code = str(file) | |
| lines = code.splitlines() | |
| line_explanations = [] | |
| for idx, line in enumerate(lines): | |
| if not line.strip(): | |
| continue | |
| prompt = f"Explain this line of code:\n{line}" | |
| response = model.generate_content(prompt) | |
| result = response.text if hasattr(response, 'text') else str(response) | |
| line_explanations.append(f"Line {idx+1}: {line}\nExplanation: {result.strip()}\n") | |
| explanations.append(f"## {filename}\n" + "\n".join(line_explanations)) | |
| return "\n\n".join(explanations) | |
| def main(): | |
| with gr.Blocks() as demo: | |
| gr.Markdown("# CodeExplainerBot (Gemini API)") | |
| code_input = gr.File(label="Upload code files", file_count="multiple", type="binary") | |
| output = gr.Textbox(label="Line-by-line Explanation", lines=20) | |
| explain_btn = gr.Button("Explain Code") | |
| explain_btn.click(fn=explain_code, inputs=[code_input, None], outputs=output) | |
| demo.launch() | |
| if __name__ == "__main__": | |
| main() | |