spagestic's picture
feat: add Gradio interfaces for vector operations; remove old vector interface file
727d361
"""
Gradio Interface for Vector operations.
"""
import gradio as gr
import numpy as np
import json
from typing import Union
def parse_vector(vector_str: str) -> np.ndarray:
try:
v = json.loads(vector_str)
arr = np.array(v, dtype=float)
if arr.ndim != 1:
raise ValueError("Vector must be 1-dimensional.")
if arr.shape[0] == 0:
raise ValueError("Vector cannot be empty.")
return arr
except (json.JSONDecodeError, TypeError, ValueError) as e_json:
try:
if not vector_str.strip():
raise ValueError("Vector input is empty.")
arr = np.array([float(x.strip()) for x in vector_str.split(',') if x.strip()], dtype=float)
if arr.shape[0] == 0:
raise ValueError("Vector cannot be empty after parsing.")
return arr
except ValueError as e_csv:
raise gr.Error(f"Invalid vector format. Use JSON (e.g., [1,2,3]) or comma-separated (e.g., 1,2,3). Error: {e_csv} (Original JSON error: {e_json})")
except Exception as e_gen:
raise gr.Error(f"General error parsing vector: {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."