Spaces:
Running
Running
Update usage_logging.py
Browse files- usage_logging.py +20 -5
usage_logging.py
CHANGED
|
@@ -113,14 +113,29 @@ def _get_client_ip(request: gr.Request) -> str:
|
|
| 113 |
|
| 114 |
|
| 115 |
def _country_lookup(ip: str) -> str:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
try:
|
| 117 |
-
|
|
|
|
| 118 |
if r.status_code == 200:
|
| 119 |
data = r.json()
|
| 120 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
except Exception:
|
| 122 |
-
|
| 123 |
-
return "Unknown"
|
| 124 |
|
| 125 |
|
| 126 |
def append_visit_to_dataset(country: str, city: str, event_type: str = "usage_start", **extra_fields):
|
|
@@ -182,7 +197,7 @@ def record_visit(request: gr.Request):
|
|
| 182 |
country=country,
|
| 183 |
city="",
|
| 184 |
event_type="usage_start",
|
| 185 |
-
country_source="
|
| 186 |
)
|
| 187 |
return
|
| 188 |
|
|
|
|
| 113 |
|
| 114 |
|
| 115 |
def _country_lookup(ip: str) -> str:
|
| 116 |
+
token = os.environ.get("IPINFO_TOKEN")
|
| 117 |
+
if not token:
|
| 118 |
+
return "Unknown"
|
| 119 |
+
|
| 120 |
try:
|
| 121 |
+
url = f"https://ipinfo.io/{ip}/json?token={token}"
|
| 122 |
+
r = requests.get(url, timeout=4)
|
| 123 |
if r.status_code == 200:
|
| 124 |
data = r.json()
|
| 125 |
+
|
| 126 |
+
# ipinfo returns country code like "US"
|
| 127 |
+
country_code = (data.get("country") or "").strip()
|
| 128 |
+
if country_code:
|
| 129 |
+
return country_code
|
| 130 |
+
|
| 131 |
+
# fallback to country name if present
|
| 132 |
+
country_name = (data.get("country_name") or "").strip()
|
| 133 |
+
if country_name:
|
| 134 |
+
return country_name
|
| 135 |
+
|
| 136 |
+
return "Unknown"
|
| 137 |
except Exception:
|
| 138 |
+
return "Unknown"
|
|
|
|
| 139 |
|
| 140 |
|
| 141 |
def append_visit_to_dataset(country: str, city: str, event_type: str = "usage_start", **extra_fields):
|
|
|
|
| 197 |
country=country,
|
| 198 |
city="",
|
| 199 |
event_type="usage_start",
|
| 200 |
+
country_source="ipinfo" if country != "Unknown" else "ipinfo_unknown"
|
| 201 |
)
|
| 202 |
return
|
| 203 |
|