ahmedtaha100 commited on
Commit
f4b993a
·
verified ·
1 Parent(s): e3dafe3

Upload github_storage.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. github_storage.py +39 -12
github_storage.py CHANGED
@@ -2,9 +2,11 @@ from __future__ import annotations
2
 
3
  import base64
4
  import csv
 
5
  import io
6
  import json
7
  import logging
 
8
  from typing import Any
9
 
10
  import requests
@@ -22,6 +24,13 @@ FIELDNAMES = [
22
  "timestamp",
23
  ]
24
 
 
 
 
 
 
 
 
25
 
26
  def _get_config() -> dict[str, str]:
27
  import os
@@ -59,7 +68,7 @@ def _get_file(repo: str, path: str, token: str, branch: str) -> tuple[str | None
59
  return content, data["sha"]
60
 
61
 
62
- def _put_file(
63
  repo: str,
64
  path: str,
65
  content: str,
@@ -76,8 +85,25 @@ def _put_file(
76
  }
77
  if sha:
78
  body["sha"] = sha
79
- resp = requests.put(url, headers=_headers(token), json=body, timeout=15)
80
- resp.raise_for_status()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
 
82
 
83
  def _ensure_branch(repo: str, token: str, branch: str) -> None:
@@ -119,7 +145,8 @@ def load_pairs() -> list[dict]:
119
 
120
  def load_existing_reviews(reviewer_id: str) -> dict[int, dict]:
121
  cfg = _get_config()
122
- path = f"{cfg['data_dir']}/reviews_{reviewer_id}.csv"
 
123
  content, _ = _get_file(cfg["repo"], path, cfg["token"], cfg["branch"])
124
  if content is None:
125
  return {}
@@ -134,7 +161,8 @@ def save_review(reviewer_id: str, pair_index: int, review: dict) -> None:
134
  cfg = _get_config()
135
  _ensure_branch(cfg["repo"], cfg["token"], cfg["branch"])
136
 
137
- path = f"{cfg['data_dir']}/reviews_{reviewer_id}.csv"
 
138
  content, sha = _get_file(cfg["repo"], path, cfg["token"], cfg["branch"])
139
 
140
  existing: dict[int, dict] = {}
@@ -151,20 +179,18 @@ def save_review(reviewer_id: str, pair_index: int, review: dict) -> None:
151
  for idx in sorted(existing.keys()):
152
  writer.writerow(existing[idx])
153
 
154
- _put_file(
155
  cfg["repo"],
156
  path,
157
  output.getvalue(),
158
  cfg["token"],
159
  cfg["branch"],
160
  sha,
161
- f"Review by {reviewer_id}: pair {pair_index}",
162
  )
163
 
164
 
165
  def append_audit_log(reviewer_id: str, pair_index: int, action: str) -> None:
166
- import time
167
-
168
  cfg = _get_config()
169
  _ensure_branch(cfg["repo"], cfg["token"], cfg["branch"])
170
 
@@ -175,15 +201,16 @@ def append_audit_log(reviewer_id: str, pair_index: int, action: str) -> None:
175
  content = "timestamp,reviewer_id,pair_index,action\n"
176
  sha = None
177
 
 
178
  timestamp = time.strftime("%Y-%m-%d %H:%M:%S UTC", time.gmtime())
179
- content += f"{timestamp},{reviewer_id},{pair_index},{action}\n"
180
 
181
- _put_file(
182
  cfg["repo"],
183
  path,
184
  content,
185
  cfg["token"],
186
  cfg["branch"],
187
  sha,
188
- f"Audit: {action} by {reviewer_id}",
189
  )
 
2
 
3
  import base64
4
  import csv
5
+ import hashlib
6
  import io
7
  import json
8
  import logging
9
+ import time
10
  from typing import Any
11
 
12
  import requests
 
24
  "timestamp",
25
  ]
26
 
27
+ MAX_RETRIES = 3
28
+ RETRY_BACKOFF = 2.0
29
+
30
+
31
+ def _safe_reviewer_id(reviewer_id: str) -> str:
32
+ return hashlib.sha256(reviewer_id.encode()).hexdigest()[:12]
33
+
34
 
35
  def _get_config() -> dict[str, str]:
36
  import os
 
68
  return content, data["sha"]
69
 
70
 
71
+ def _put_file_with_retry(
72
  repo: str,
73
  path: str,
74
  content: str,
 
85
  }
86
  if sha:
87
  body["sha"] = sha
88
+
89
+ last_error: Exception | None = None
90
+ for attempt in range(MAX_RETRIES):
91
+ try:
92
+ resp = requests.put(url, headers=_headers(token), json=body, timeout=15)
93
+ if resp.status_code == 409:
94
+ _, fresh_sha = _get_file(repo, path, token, branch)
95
+ if fresh_sha:
96
+ body["sha"] = fresh_sha
97
+ last_error = requests.HTTPError(response=resp)
98
+ time.sleep(RETRY_BACKOFF ** attempt)
99
+ continue
100
+ resp.raise_for_status()
101
+ return
102
+ except requests.RequestException as e:
103
+ last_error = e
104
+ if attempt < MAX_RETRIES - 1:
105
+ time.sleep(RETRY_BACKOFF ** attempt)
106
+ raise last_error # type: ignore[misc]
107
 
108
 
109
  def _ensure_branch(repo: str, token: str, branch: str) -> None:
 
145
 
146
  def load_existing_reviews(reviewer_id: str) -> dict[int, dict]:
147
  cfg = _get_config()
148
+ safe_id = _safe_reviewer_id(reviewer_id)
149
+ path = f"{cfg['data_dir']}/reviews_{safe_id}.csv"
150
  content, _ = _get_file(cfg["repo"], path, cfg["token"], cfg["branch"])
151
  if content is None:
152
  return {}
 
161
  cfg = _get_config()
162
  _ensure_branch(cfg["repo"], cfg["token"], cfg["branch"])
163
 
164
+ safe_id = _safe_reviewer_id(reviewer_id)
165
+ path = f"{cfg['data_dir']}/reviews_{safe_id}.csv"
166
  content, sha = _get_file(cfg["repo"], path, cfg["token"], cfg["branch"])
167
 
168
  existing: dict[int, dict] = {}
 
179
  for idx in sorted(existing.keys()):
180
  writer.writerow(existing[idx])
181
 
182
+ _put_file_with_retry(
183
  cfg["repo"],
184
  path,
185
  output.getvalue(),
186
  cfg["token"],
187
  cfg["branch"],
188
  sha,
189
+ f"Review by {safe_id}: pair {pair_index}",
190
  )
191
 
192
 
193
  def append_audit_log(reviewer_id: str, pair_index: int, action: str) -> None:
 
 
194
  cfg = _get_config()
195
  _ensure_branch(cfg["repo"], cfg["token"], cfg["branch"])
196
 
 
201
  content = "timestamp,reviewer_id,pair_index,action\n"
202
  sha = None
203
 
204
+ safe_id = _safe_reviewer_id(reviewer_id)
205
  timestamp = time.strftime("%Y-%m-%d %H:%M:%S UTC", time.gmtime())
206
+ content += f"{timestamp},{safe_id},{pair_index},{action}\n"
207
 
208
+ _put_file_with_retry(
209
  cfg["repo"],
210
  path,
211
  content,
212
  cfg["token"],
213
  cfg["branch"],
214
  sha,
215
+ f"Audit: {action} by {safe_id}",
216
  )