aparke21 commited on
Commit
ba34acd
·
verified ·
1 Parent(s): d2b67df

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +59 -40
app.py CHANGED
@@ -1,61 +1,79 @@
1
  import gradio as gr
2
  import os
3
  from datetime import datetime
4
- from huggingface_hub import HfApi
5
 
6
- # ----- CONFIG -----
7
- # Make sure this matches your Space URL exactly:
8
- # https://huggingface.co/spaces/aparke21/simple_gradio_app
9
- REPO_ID = "aparke21/simple_gradio_app" # <username>/<space-name>
10
- REPO_TYPE = "space"
11
- LOG_LOCAL_DIR = "temp_logs"
12
- LOG_LOCAL_PATH = os.path.join(LOG_LOCAL_DIR, "logs.txt")
13
- LOG_REMOTE_PATH = "internal_logs/logs.txt" # where it will live in the Space repo
14
 
15
 
16
- def _append_to_local_log(message: str) -> None:
17
- """Append a log line to a local file inside the container."""
18
- os.makedirs(LOG_LOCAL_DIR, exist_ok=True)
19
- timestamp = datetime.utcnow().isoformat()
20
- line = f"{timestamp} | {message}\n"
21
- with open(LOG_LOCAL_PATH, "a") as f:
22
- f.write(line)
23
 
24
 
25
- def _upload_log_to_repo() -> None:
26
- """Upload the local log file to the Space repo (overwriting logs.txt)."""
27
- token = os.getenv("HF_TOKEN")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  if token is None:
29
- # If the token isn't set, just skip uploading but don't break the app.
30
- print("[LOGGING] HF_TOKEN not set; skipping upload to repo.")
31
- return
32
 
33
- if not os.path.exists(LOG_LOCAL_PATH):
34
- print("[LOGGING] Local log file does not exist; nothing to upload.")
35
- return
 
 
 
 
 
36
 
 
37
  try:
38
- api = HfApi(token=token)
39
  api.upload_file(
40
- path_or_fileobj=LOG_LOCAL_PATH,
41
- repo_id=REPO_ID,
42
- repo_type=REPO_TYPE,
43
- path_in_repo=LOG_REMOTE_PATH,
44
  )
45
- print(f"[LOGGING] Uploaded log file to {REPO_ID}/{LOG_REMOTE_PATH}")
46
  except Exception as e:
47
- # Don't crash the app if upload fails; just log the error.
48
- print("[LOGGING] Failed to upload log file:", e)
49
 
50
 
51
  def greet(name: str) -> str:
52
- # 1. Log this interaction locally
53
- _append_to_local_log(f"Greet called with name='{name}'")
54
-
55
- # 2. Sync the log to your Space repo (so you can see it later in Files & Versions)
56
- _upload_log_to_repo()
57
-
58
- # 3. Normal app behavior
59
  return "Hello " + name + "!!"
60
 
61
 
@@ -63,3 +81,4 @@ demo = gr.Interface(fn=greet, inputs="text", outputs="text")
63
 
64
  if __name__ == "__main__":
65
  demo.launch()
 
 
1
  import gradio as gr
2
  import os
3
  from datetime import datetime
4
+ from huggingface_hub import HfApi, hf_hub_download, HfHubHTTPError
5
 
6
+ # ===== CONFIG =====
7
+ LOG_REPO_ID = "aparke21/simple_gradio_app_logs" # <-- your dataset repo
8
+ LOG_REPO_TYPE = "dataset"
9
+ LOG_FILE_NAME = "logs.txt"
 
 
 
 
10
 
11
 
12
+ def _get_token():
13
+ token = os.getenv("HF_TOKEN")
14
+ if token is None:
15
+ print("[LOGGING] HF_TOKEN not set; skipping logging.")
16
+ return token
 
 
17
 
18
 
19
+ def _download_existing_log(token):
20
+ """Try to download existing logs.txt from the dataset repo.
21
+ Returns local path, or a new empty file path."""
22
+ local_path = "logs_buffer.txt"
23
+
24
+ try:
25
+ cached_path = hf_hub_download(
26
+ repo_id=LOG_REPO_ID,
27
+ repo_type=LOG_REPO_TYPE,
28
+ filename=LOG_FILE_NAME,
29
+ token=token,
30
+ )
31
+ # Copy cached file to our working file
32
+ with open(cached_path, "r") as src, open(local_path, "w") as dst:
33
+ dst.write(src.read())
34
+ print("[LOGGING] Existing log downloaded and loaded.")
35
+ except HfHubHTTPError as e:
36
+ # Likely file does not exist yet (404)
37
+ print("[LOGGING] No existing log found, starting a new one.", e)
38
+ # Ensure empty file
39
+ with open(local_path, "w") as f:
40
+ f.write("")
41
+
42
+ return local_path
43
+
44
+
45
+ def _append_and_upload_log(message: str):
46
+ token = _get_token()
47
  if token is None:
48
+ return # no token, cannot log
49
+
50
+ api = HfApi(token=token)
51
 
52
+ # 1. Get current logs from the dataset (if any)
53
+ local_path = _download_existing_log(token)
54
+
55
+ # 2. Append new log line
56
+ timestamp = datetime.utcnow().isoformat()
57
+ line = f"{timestamp} | {message}\n"
58
+ with open(local_path, "a") as f:
59
+ f.write(line)
60
 
61
+ # 3. Upload updated log file back to dataset repo
62
  try:
 
63
  api.upload_file(
64
+ path_or_fileobj=local_path,
65
+ repo_id=LOG_REPO_ID,
66
+ repo_type=LOG_REPO_TYPE,
67
+ path_in_repo=LOG_FILE_NAME,
68
  )
69
+ print(f"[LOGGING] Uploaded updated logs to {LOG_REPO_ID}/{LOG_FILE_NAME}")
70
  except Exception as e:
71
+ print("[LOGGING] Failed to upload logs:", e)
 
72
 
73
 
74
  def greet(name: str) -> str:
75
+ # Log the interaction (quietly, server-side)
76
+ _append_and_upload_log(f"greet called with name='{name}'")
 
 
 
 
 
77
  return "Hello " + name + "!!"
78
 
79
 
 
81
 
82
  if __name__ == "__main__":
83
  demo.launch()
84
+