xoarissa commited on
Commit
1a2bb69
·
1 Parent(s): a9c43e1

Fixed color issue by converting RGBA to HEX

Browse files
Files changed (1) hide show
  1. app.py +18 -22
app.py CHANGED
@@ -2,22 +2,23 @@ import numpy as np
2
  import matplotlib.pyplot as plt
3
  import gradio as gr
4
  import os
 
5
 
6
- # Function to convert HEX color to normalized RGB tuple
7
- def hex_to_rgb(hex_color):
8
- """Convert HEX color (#RRGGBB) to Matplotlib RGB tuple (R, G, B)."""
9
- hex_color = hex_color.lstrip("#") # Remove '#' if present
10
- rgb = tuple(int(hex_color[i:i+2], 16) / 255 for i in (0, 2, 4)) # Normalize (0-1)
11
- return rgb # Matplotlib needs RGB values between 0-1
 
12
 
13
  def plot_function(func_str, x_min, x_max, resolution, color, linestyle, grid):
14
  try:
15
- # Ensure color is valid; fallback to black if empty
16
- if not color or not color.startswith("#") or len(color) != 7:
17
- color = "#000000" # Default to black
18
 
19
- # Convert HEX to RGB and normalize it
20
- color_rgb = hex_to_rgb(color)
 
21
 
22
  x_values = np.linspace(x_min, x_max, resolution)
23
  functions = func_str.split(",")
@@ -29,8 +30,7 @@ def plot_function(func_str, x_min, x_max, resolution, color, linestyle, grid):
29
  func = lambda x: eval(func_text, {"x": x, "np": np})
30
  y_values = func(x_values)
31
 
32
- # Use normalized RGB color for Matplotlib
33
- plt.plot(x_values, y_values, label=f"f(x) = {func_text}", color=color_rgb, linestyle=linestyle)
34
 
35
  plt.xlabel("x")
36
  plt.ylabel("f(x)")
@@ -39,19 +39,15 @@ def plot_function(func_str, x_min, x_max, resolution, color, linestyle, grid):
39
  if grid:
40
  plt.grid()
41
 
42
- # Save the plot and return absolute path
43
  plot_filename = "high_res_plot.png"
44
- abs_path = os.path.abspath(plot_filename) # Convert to absolute path
45
  plt.savefig(abs_path, dpi=300)
46
  plt.close()
47
 
48
- # Ensure the file exists before returning
49
- if os.path.exists(abs_path):
50
- return abs_path, abs_path
51
- else:
52
- return "Error: Plot file was not created", None
53
 
54
  except Exception as e:
 
55
  return f"Error: {e}", None
56
 
57
  # Gradio Interface
@@ -64,8 +60,8 @@ with gr.Blocks() as demo:
64
  x_min = gr.Number(label="X Min", value=-10)
65
  x_max = gr.Number(label="X Max", value=10)
66
  resolution = gr.Slider(10, 1000, step=10, label="Resolution", value=100)
67
- color = gr.ColorPicker(label="Line Color", value="#000000") # Default to black
68
- linestyle = gr.Dropdown(["solid", "dashed", "dotted", "dashdot"], label="Line Style")
69
  grid = gr.Checkbox(label="Show Grid", value=True)
70
  submit_button = gr.Button("Plot Function")
71
 
 
2
  import matplotlib.pyplot as plt
3
  import gradio as gr
4
  import os
5
+ import re
6
 
7
+
8
+ def rgba_to_hex(rgba_str):
9
+ """Converts an RGBA string (e.g., 'rgba(24.6, 187.3, 155.0, 1)') to a HEX color."""
10
+ match = re.match(r"rgba\((\d+(\.\d+)?),\s*(\d+(\.\d+)?),\s*(\d+(\.\d+)?),\s*\d+(\.\d+)?\)", rgba_str)
11
+ if match:
12
+ r, g, b = map(lambda x: int(float(x)), [match.group(1), match.group(3), match.group(5)])
13
+ return "#{:02x}{:02x}{:02x}".format(r, g, b)
14
 
15
  def plot_function(func_str, x_min, x_max, resolution, color, linestyle, grid):
16
  try:
17
+ print(f"DEBUG: Received color - {color}")
 
 
18
 
19
+ if "rgba" in color:
20
+ color = rgba_to_hex(color)
21
+ print(f"DEBUG: Using fixed color - {color}")
22
 
23
  x_values = np.linspace(x_min, x_max, resolution)
24
  functions = func_str.split(",")
 
30
  func = lambda x: eval(func_text, {"x": x, "np": np})
31
  y_values = func(x_values)
32
 
33
+ plt.plot(x_values, y_values, label=f"f(x) = {func_text}", color=color, linestyle=linestyle)
 
34
 
35
  plt.xlabel("x")
36
  plt.ylabel("f(x)")
 
39
  if grid:
40
  plt.grid()
41
 
 
42
  plot_filename = "high_res_plot.png"
43
+ abs_path = os.path.abspath(plot_filename)
44
  plt.savefig(abs_path, dpi=300)
45
  plt.close()
46
 
47
+ return abs_path, abs_path if os.path.exists(abs_path) else ("Error: Plot file was not created", None)
 
 
 
 
48
 
49
  except Exception as e:
50
+ print(f"ERROR: {e}")
51
  return f"Error: {e}", None
52
 
53
  # Gradio Interface
 
60
  x_min = gr.Number(label="X Min", value=-10)
61
  x_max = gr.Number(label="X Max", value=10)
62
  resolution = gr.Slider(10, 1000, step=10, label="Resolution", value=100)
63
+ color = gr.ColorPicker(label="Line Color", value="#ff0000") # Default to red
64
+ linestyle = gr.Dropdown(["solid", "dashed", "dotted", "dashdot"], label="Line Style", value="solid")
65
  grid = gr.Checkbox(label="Show Grid", value=True)
66
  submit_button = gr.Button("Plot Function")
67