import gradio as gr import matplotlib.pyplot as plt import numpy as np from sympy import symbols, Eq, solve, im import google.generativeai as genai import os # Initialize Gemini API (consider moving the API key to an environment variable) API_KEY = "AIzaSyDhXQfnHB0u1WFCheBa3Ii98uk6RgnxWpY" # Replace with your API key if needed genai.configure(api_key=API_KEY) model = genai.GenerativeModel("generative") # Global state for storing plotted points def create_base_figure(): fig, ax = plt.subplots(figsize=(6, 5)) ax.set_facecolor("white") ax.set_xticks(np.arange(-10, 11, 1)) ax.set_yticks(np.arange(-10, 11, 1)) ax.grid(True, linestyle='-', linewidth=0.5, color='gray') ax.axhline(0, color='black', linewidth=1) ax.axvline(0, color='black', linewidth=1) ax.set_xlim(-10, 10) ax.set_ylim(-10, 10) return fig, ax def plot_point(x_val, y_val, state): try: x = float(x_val) y = float(y_val) except Exception: return None, state, "Error: Enter valid numbers for x and y." state = state + [(x, y)] fig, ax = create_base_figure() if len(state) > 1: xs, ys = zip(*state) ax.plot(xs, ys, 'bo-', markersize=8, linewidth=2) else: ax.plot(x, y, 'bo', markersize=8) return fig, state, "Point added." def clear_graph(): fig, ax = create_base_figure() state = [] return fig, state, "Graph cleared." def solve_graph_equation(equation_str): try: x = symbols('x') # Safely evaluate the input (e.g., "x**2 - 4") y_expr = eval(equation_str, {"x": x}) solutions = solve(Eq(y_expr, 0), x) x_vals = np.linspace(-10, 10, 500) y_vals = [y_expr.subs(x, xi) for xi in x_vals] fig, ax = create_base_figure() ax.plot(x_vals, y_vals, label=f"y = {equation_str}", color='blue', linewidth=2) real_solutions = [] for sol in solutions: if im(sol) == 0: real_solutions.append(sol) ax.plot(sol, 0, 'ro', markersize=8) ax.text(sol, 0.5, f"({sol:.2f}, 0)", fontsize=10, ha='center') ax.legend(loc="upper right") explanation = f"Equation: y = {equation_str}\n\n" if real_solutions: explanation += f"Real solutions: {real_solutions}\n\nThe equation was solved by finding the x-values where y = 0." else: explanation += "No real solutions found. (Complex roots)" return fig, explanation except Exception as e: return None, f"Error solving equation: {e}" def ask_ai(question): if not question.strip(): return "Error: Enter a question." try: response = model.generate_content(question) return response.text.strip() if response else "No response from AI." except Exception as e: return f"Error: {e}" # Custom CSS to emulate your original tkinter design css = """ body {background-color: #2c3e50; font-family: Arial, sans-serif; color: white;} #graph_canvas {border: 2px solid #ccc; margin: 10px;} .control-panel {background-color: #34495e; padding: 15px; border-radius: 5px; margin: 10px; } .explanation-box {background-color: #ecf0f1; padding: 10px; border: 2px solid #ccc; margin-bottom: 15px; color: #2c3e50; } """ with gr.Blocks(css=css, title="Graph Theory AI with Gemini Integration") as demo: gr.Markdown("## Graph Theory AI with Gemini Integration") with gr.Row(): # Left column: Graph Display graph_output = gr.Plot(label="Graph", elem_id="graph_canvas") # Right column: Control Panel (mimicking your sidebar) with gr.Column(elem_classes="control-panel"): # Explanation Box (like your explanation frame) explanation_text = gr.Textbox(label="Explanation", lines=8, interactive=False, elem_classes="explanation-box") # Plot Point Section gr.Markdown("### Plot Point") x_input = gr.Textbox(label="X", placeholder="Enter x value") y_input = gr.Textbox(label="Y", placeholder="Enter y value") with gr.Row(): plot_button = gr.Button("Plot Point") clear_button = gr.Button("Clear Graph") # Equation Solver Section gr.Markdown("### Solve Equation") equation_input = gr.Textbox(label="Enter Equation (e.g., x**2 - 4)", placeholder="x**2 - 4") solve_button = gr.Button("Solve & Plot Equation") equation_explanation = gr.Textbox(label="Equation Explanation", lines=10, interactive=False) # AI Section gr.Markdown("### Ask AI") ai_question = gr.Textbox(label="Ask the AI Anything", lines=3, placeholder="Enter your question") ask_button = gr.Button("Ask AI") ai_response = gr.Textbox(label="AI Response", lines=10, interactive=False) # Maintain state for plotted points state_points = gr.State([]) # Define interactions plot_button.click(fn=plot_point, inputs=[x_input, y_input, state_points], outputs=[graph_output, state_points, explanation_text]) clear_button.click(fn=clear_graph, inputs=None, outputs=[graph_output, state_points, explanation_text]) solve_button.click(fn=solve_graph_equation, inputs=equation_input, outputs=[graph_output, equation_explanation]) ask_button.click(fn=ask_ai, inputs=ai_question, outputs=ai_response) demo.launch(share=True)