File size: 1,698 Bytes
e804d56
aa6ef3b
 
 
e804d56
aa6ef3b
 
 
e804d56
aa6ef3b
 
e804d56
 
 
19dc357
 
 
 
 
 
e804d56
 
 
 
aa6ef3b
 
 
 
e804d56
 
 
 
 
 
aa6ef3b
915bcb7
e804d56
 
aa6ef3b
e804d56
 
 
 
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
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()