dynamic-hfspaces / shared_functions.py
LPX55
Refactor app.py to utilize shared functions for greeting, calculation, and image processing, enhancing modularity and code reuse. Introduce space loading tabs for dynamic integration of popular Hugging Face Spaces.
4cc700d
import tempfile
import pandas as pd
import numpy as np
import gradio as gr
def greet(name="Stranger", intensity=1, exclaim=False):
greeting = f"Hello, {name}{'!' * int(intensity)}"
if exclaim:
greeting = greeting.upper()
return greeting
def calculator(num1, operation, num2):
if operation == "add":
result = num1 + num2
elif operation == "subtract":
result = num1 - num2
elif operation == "multiply":
result = num1 * num2
elif operation == "divide":
if num2 == 0:
raise gr.Error("Cannot divide by zero!")
result = num1 / num2
return result
def sepia(input_img):
sepia_filter = np.array([
[0.393, 0.769, 0.189],
[0.349, 0.686, 0.168],
[0.272, 0.534, 0.131]
])
sepia_img = input_img @ sepia_filter.T
sepia_img = np.clip(sepia_img, 0, 255).astype(np.uint8)
return sepia_img
def download_text(text):
if not text:
text = ""
with tempfile.NamedTemporaryFile(delete=False, suffix=".txt", mode="w", encoding="utf-8") as f:
f.write(text)
return f.name
def download_csv(result):
if result is None:
result = ""
df = pd.DataFrame({"Result": [result]})
with tempfile.NamedTemporaryFile(delete=False, suffix=".csv", mode="w", encoding="utf-8") as f:
df.to_csv(f, index=False)
return f.name