marwanahmed99/Software_Engineering_Coach
0
1import os2import time3from typing import List, Tuple, Optional4import google.generativeai as genai5import gradio as gr6from PIL import Image7 8# 1. Configuration & Secrets9# This pulls directly from your Hugging Face "Secrets" section10GOOGLE_API_KEY = os.environ.get("GEMINI_API_KEY")11MODEL_NAME = "gemini-2.0-flash-exp"12IMAGE_WIDTH = 51213 14# 2. The Coaching Persona15COACH_SYSTEM_PROMPT = """16You are a Senior Software Engineering Coach. Your goal is to mentor developers 17by analyzing their code or technical queries through the lens of:18- SOLID, DRY, and KISS principles.19- Security, Scalability, and Maintainability.20- Modern architectural patterns (Microservices, Event-driven, etc.).21 22When providing feedback:231. Don't just give the answer; explain the 'why' to foster growth.242. Identify potential 'code smells' or anti-patterns.253. Provide high-quality, idiomatic code examples.264. If a diagram is provided, analyze the architectural flow or UI/UX logic.27"""28 29# 3. Core Logic30def preprocess_image(image: Image.Image) -> Image.Image:31 if image is None:32 return None33 aspect_ratio = image.height / image.width34 return image.resize((IMAGE_WIDTH, int(IMAGE_WIDTH * aspect_ratio)))35 36def bot(37 image_prompt: Optional[Image.Image],38 temperature: float,39 max_output_tokens: int,40 top_p: float,41 chatbot: List[Tuple[str, str]]42):43 if not GOOGLE_API_KEY:44 chatbot[-1][1] = "Error: GEMINI_API_KEY not found in Hugging Face Secrets."45 yield chatbot46 return47 48 # Initialize the model with the Coach System Prompt49 genai.configure(api_key=GOOGLE_API_KEY)50 model = genai.GenerativeModel(51 model_name=MODEL_NAME, 52 system_instruction=COACH_SYSTEM_PROMPT53 )54 55 text_prompt = chatbot[-1][0].strip() if chatbot[-1][0] else ""56 57 # Prepare Multimodal Inputs58 inputs = []59 if text_prompt:60 inputs.append(text_prompt)61 if image_prompt:62 inputs.append(preprocess_image(image_prompt))63 if not text_prompt:64 inputs[0] = "Please analyze this technical image or code snippet."65 66 try:67 response = model.generate_content(68 inputs,69 stream=True,70 generation_config=genai.types.GenerationConfig(71 temperature=temperature,72 max_output_tokens=max_output_tokens,73 top_p=top_p,74 )75 )76 77 chatbot[-1][1] = ""78 for chunk in response:79 chatbot[-1][1] += chunk.text80 time.sleep(0.005) # Smoother streaming81 yield chatbot82 except Exception as e:83 chatbot[-1][1] = f"Coach encountered an error: {str(e)}"84 yield chatbot85 86# 4. Modernized Gradio UI87with gr.Blocks(theme=gr.themes.Default(primary_hue="blue", neutral_hue="gray")) as demo:88 gr.Markdown("""89 # ๐จโ๐ป Software Engineering Coach90 *Level up your code with AI-driven mentorship. Paste your code, upload diagrams, or ask architectural questions.*91 """)92 93 with gr.Row():94 with gr.Column(scale=3):95 chatbot_component = gr.Chatbot(96 label="Coaching Session", 97 height=550, 98 show_copy_button=True99 )100 with gr.Row():101 text_input = gr.Textbox(102 placeholder="Ask about design patterns, refactor code, or debug logic...",103 label="Message the Coach",104 scale=4,105 lines=2106 )107 submit_btn = gr.Button("Analyze", variant="primary", scale=1)108 109 with gr.Column(scale=1):110 image_input = gr.Image(type="pil", label="Visual Context (Code Scrsht/Diagram)")111 112 with gr.Accordion("Fine-tune Mentorship", open=False):113 temp = gr.Slider(0, 1.0, 0.3, label="Creativity/Randomness")114 tokens = gr.Slider(100, 4096, 2048, label="Max Response Length")115 top_p_slider = gr.Slider(0, 1, 0.95, label="Top-P")116 117 gr.Markdown("---")118 gr.Markdown("### Examples")119 gr.Examples(120 examples=[121 ["Refactor this for better maintainability."],122 ["Explain the Repository Pattern with a Python example."],123 ["What are the security risks in this code?"]124 ],125 inputs=text_input126 )127 128 # Event Handlers129 def user_msg(msg, history):130 return "", history + [[msg, None]]131 132 submit_btn.click(133 user_msg, [text_input, chatbot_component], [text_input, chatbot_component]134 ).then(135 bot, 136 [image_input, temp, tokens, top_p_slider, chatbot_component], 137 chatbot_component138 )139 140if __name__ == "__main__":141 demo.launch()