File size: 2,391 Bytes
c555dda
e9c815a
312555e
e00c4cc
 
312555e
ba34acd
 
 
 
f375998
 
ba34acd
 
 
 
 
c555dda
 
ba34acd
01861c1
 
ba34acd
 
 
 
 
 
 
 
 
 
 
 
 
01861c1
 
ba34acd
 
 
 
 
 
01861c1
ba34acd
 
f375998
ba34acd
 
 
e9c815a
ba34acd
 
 
 
 
 
 
 
e9c815a
ba34acd
f375998
 
ba34acd
 
 
 
f375998
ba34acd
f375998
ba34acd
e9c815a
c555dda
f375998
ba34acd
 
f375998
e9c815a
 
f375998
312555e
f375998
 
ba34acd
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
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()