Spaces:
Runtime error
Runtime error
File size: 2,157 Bytes
ff0d3b3 |
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 |
"""
Utility functions for matrix parsing and formatting in Gradio applications.
"""
import gradio as gr
import numpy as np
import json
from typing import Union
def parse_matrix(matrix_str: str, allow_empty_rows_cols=False) -> np.ndarray:
try:
m = json.loads(matrix_str)
arr = np.array(m, dtype=float)
if not allow_empty_rows_cols and (arr.shape[0] == 0 or (arr.ndim > 1 and arr.shape[1] == 0)):
raise ValueError("Matrix cannot have zero rows or columns.")
if arr.ndim == 1 and arr.shape[0] > 0:
arr = arr.reshape(1, -1)
elif arr.ndim == 0 and not allow_empty_rows_cols:
raise ValueError("Input is a scalar, not a matrix.")
return arr
except (json.JSONDecodeError, TypeError, ValueError) as e_json:
try:
rows = [list(map(float, row.split(','))) for row in matrix_str.split(';') if row.strip()]
if not rows and not allow_empty_rows_cols:
raise ValueError("Matrix input is empty.")
if not rows and allow_empty_rows_cols:
return np.array([])
if len(rows) > 1:
first_row_len = len(rows[0])
if not all(len(r) == first_row_len for r in rows):
raise ValueError("All rows must have the same number of columns.")
arr = np.array(rows, dtype=float)
if not allow_empty_rows_cols and (arr.shape[0] == 0 or (arr.ndim > 1 and arr.shape[1] == 0)):
raise ValueError("Matrix cannot have zero rows or columns after parsing.")
return arr
except ValueError as e_csv:
raise gr.Error(f"Invalid matrix format. Use JSON (e.g., [[1,2],[3,4]]) or comma/semicolon (e.g., 1,2;3,4). Error: {e_csv} (Original JSON error: {e_json})")
except Exception as e_gen:
raise gr.Error(f"General error parsing matrix: {e_gen}")
def format_output(data: Union[np.ndarray, float, str]) -> str:
if isinstance(data, np.ndarray):
return str(data.tolist())
elif isinstance(data, (float, int, str)):
return str(data)
return "Output type not recognized."
|