import gradio as gr import os def convert_temperature(temp: str, unit: str) -> dict[str, str]: """ Converts a temperature value from one unit to Celsius, Fahrenheit, and Kelvin. This function takes a temperature value as a string and its unit, performs the conversion, and returns the equivalent temperatures in all three units as formatted strings in a dictionary. Designed for use in a Gradio interface and as an MCP tool. Args: temp (str): The temperature value as a string (e.g., '25', '-10.5'). Must be convertible to a float. unit (str): The unit of the input temperature. Must be one of 'Celsius', 'Fahrenheit', or 'Kelvin'. Returns: dict[str, str]: A dictionary with three keys: - 'celsius': Temperature in Celsius (e.g., '25.00 °C') or 'Invalid' if input is invalid. - 'fahrenheit': Temperature in Fahrenheit (e.g., '77.00 °F') or 'Invalid' if input is invalid. - 'kelvin': Temperature in Kelvin (e.g., '298.15 K') or 'Invalid' if input is invalid. Raises: ValueError: If the temp input cannot be converted to a float. """ try: temp = float(temp) if unit == "Celsius": celsius = temp fahrenheit = (temp * 9/5) + 32 kelvin = temp + 273.15 elif unit == "Fahrenheit": celsius = (temp - 32) * 5/9 fahrenheit = temp kelvin = celsius + 273.15 else: # Kelvin celsius = temp - 273.15 fahrenheit = (celsius * 9/5) + 32 kelvin = temp return { "celsius": f"{celsius:.2f} °C", "fahrenheit": f"{fahrenheit:.2f} °F", "kelvin": f"{kelvin:.2f} K" } except ValueError: return {"celsius": "Invalid", "fahrenheit": "Invalid", "kelvin": "Invalid"} def map_output(result: dict[str, str]) -> list[str]: """ Maps the dictionary output of convert_temperature to a list for Gradio outputs. Args: result (dict[str, str]): The dictionary containing temperature values. Returns: list[str]: A list of temperature values in order [celsius, fahrenheit, kelvin]. """ return [result["celsius"], result["fahrenheit"], result["kelvin"]] # Debug prints print("Gradio Version:", gr.__version__) print("MCP Server Configured:", os.getenv("GRADIO_MCP_SERVER", "False")) # Define the Gradio interface with gr.Blocks() as app: gr.Markdown("# Temperature Converter") with gr.Row(): temp_input = gr.Textbox(label="Enter Temperature", placeholder="e.g., 25") unit_dropdown = gr.Dropdown( choices=["Celsius", "Fahrenheit", "Kelvin"], label="Select Unit", value="Celsius" ) convert_button = gr.Button("Convert") with gr.Row(): celsius_output = gr.Textbox(label="Celsius") fahrenheit_output = gr.Textbox(label="Fahrenheit") kelvin_output = gr.Textbox(label="Kelvin") convert_button.click( fn=lambda temp, unit: map_output(convert_temperature(temp, unit)), inputs=[temp_input, unit_dropdown], outputs=[celsius_output, fahrenheit_output, kelvin_output], api_name="/convert_temperature" ) # Launch the app with MCP server enabled app.launch(mcp_server=True)