File size: 5,550 Bytes
1c778ab fa40aaf 1c778ab fa40aaf c33c5aa fa40aaf c33c5aa fa40aaf c33c5aa 1c778ab c33c5aa 1c778ab fa40aaf 1c778ab fa40aaf c33c5aa 1c778ab c33c5aa 1c778ab c33c5aa 1c778ab c33c5aa 1c778ab c33c5aa 1c778ab c33c5aa 1c778ab c33c5aa fa40aaf c33c5aa 1c778ab fa40aaf 1c778ab c33c5aa fa40aaf 1c778ab fa40aaf 1c778ab fa40aaf 1c778ab fa40aaf c33c5aa fa40aaf c33c5aa 1c778ab fa40aaf 1c778ab fa40aaf 1c778ab c33c5aa fa40aaf c33c5aa fa40aaf 1c778ab c33c5aa 1c778ab c33c5aa 1c778ab c33c5aa 1c778ab c33c5aa 1c778ab c33c5aa 1c778ab c33c5aa 1c778ab c33c5aa |
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 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 |
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)
|