aparke21's picture
Update app.py
01861c1 verified
import gradio as gr
import os
from datetime import datetime
from huggingface_hub import HfApi, hf_hub_download
# ===== CONFIG =====
LOG_REPO_ID = "aparke21/simple_gradio_app_logs" # <-- your dataset repo
LOG_REPO_TYPE = "dataset"
LOG_FILE_NAME = "logs.txt"
def _get_token():
token = os.getenv("HF_TOKEN")
if token is None:
print("[LOGGING] HF_TOKEN not set; skipping logging.")
return token
def _download_existing_log(token):
"""Try to download existing logs.txt from the dataset repo.
Returns local path, or a new empty file path if download fails."""
local_path = "logs_buffer.txt"
try:
cached_path = hf_hub_download(
repo_id=LOG_REPO_ID,
repo_type=LOG_REPO_TYPE,
filename=LOG_FILE_NAME,
token=token,
)
# Copy cached file to our working file
with open(cached_path, "r") as src, open(local_path, "w") as dst:
dst.write(src.read())
print("[LOGGING] Existing log downloaded and loaded.")
except Exception as e: # <-- No special error class needed
print("[LOGGING] No existing log found or download failed:", e)
with open(local_path, "w") as f:
f.write("")
return local_path
def _append_and_upload_log(message: str):
token = _get_token()
if token is None:
return # no token, cannot log
api = HfApi(token=token)
# 1. Get current logs from the dataset (if any)
local_path = _download_existing_log(token)
# 2. Append new log line
timestamp = datetime.utcnow().isoformat()
line = f"{timestamp} | {message}\n"
with open(local_path, "a") as f:
f.write(line)
# 3. Upload updated log file back to dataset repo
try:
api.upload_file(
path_or_fileobj=local_path,
repo_id=LOG_REPO_ID,
repo_type=LOG_REPO_TYPE,
path_in_repo=LOG_FILE_NAME,
)
print(f"[LOGGING] Uploaded updated logs to {LOG_REPO_ID}/{LOG_FILE_NAME}")
except Exception as e:
print("[LOGGING] Failed to upload logs:", e)
def greet(name: str) -> str:
# Log the interaction (quietly, server-side)
_append_and_upload_log(f"greet called with name='{name}'")
return "Hello " + name + "!!"
demo = gr.Interface(fn=greet, inputs="text", outputs="text")
if __name__ == "__main__":
demo.launch()