aparke21 commited on
Commit
f375998
·
verified ·
1 Parent(s): 1995af4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +51 -24
app.py CHANGED
@@ -1,38 +1,65 @@
1
  import gradio as gr
2
  import os
3
  from datetime import datetime
 
4
 
5
- def write_log(message):
6
- os.makedirs("/data", exist_ok=True)
7
- log_path = "/data/logs.txt"
 
 
 
 
 
 
 
 
 
 
8
  timestamp = datetime.utcnow().isoformat()
9
- with open(log_path, "a") as f:
10
- f.write(f"{timestamp} - {message}\n")
 
11
 
12
- def greet(name):
13
- write_log(f"Greeted: {name}")
14
- return "Hello " + name + "!!"
15
 
16
- def download_logs():
17
- log_path = "/data/logs.txt"
18
- if os.path.exists(log_path):
19
- return log_path
20
- return None
 
 
21
 
22
- with gr.Blocks() as demo:
23
- gr.Markdown("## Greeting App with Persistent Logs (/data)")
 
24
 
25
- with gr.Row():
26
- name_input = gr.Textbox(label="Enter your name")
27
- greet_button = gr.Button("Greet")
28
- greet_output = gr.Textbox(label="Greeting")
 
 
 
 
 
 
 
 
29
 
30
- greet_button.click(fn=greet, inputs=name_input, outputs=greet_output)
31
 
32
- download_button = gr.Button("Download Logs")
33
- log_file_output = gr.File(label="Logs File")
 
 
 
 
 
 
 
34
 
35
- download_button.click(fn=download_logs, inputs=None, outputs=log_file_output)
36
 
37
- demo.launch(allowed_paths=["/data"])
38
 
 
 
 
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
 
62
+ demo = gr.Interface(fn=greet, inputs="text", outputs="text")
63
 
64
+ if __name__ == "__main__":
65
+ demo.launch()