File size: 1,983 Bytes
a2c64e7 | 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 | #!/usr/bin/env python3
"""
Contoh: Upload file menggunakan Python + requests
Cara jalankan:
python3 examples/python-requests.py
"""
import requests
import os
import sys
from pathlib import Path
# Konfigurasi
API_URL = 'http://localhost:3000/api/upload'
HF_TOKEN = os.getenv('HF_TOKEN', 'your_hf_token_here')
REPO_ID = os.getenv('HF_REPO_ID', 'username/dataset-name')
FILE_PATH = './examples/sample-data.csv'
def upload_file():
"""Upload file ke API"""
# Validasi file
if not Path(FILE_PATH).exists():
print(f'β File tidak ditemukan: {FILE_PATH}')
print('π Membuat file contoh...')
with open(FILE_PATH, 'w') as f:
f.write('id,name,value\n')
f.write('1,Alice,100\n')
f.write('2,Bob,200\n')
try:
# Setup request
with open(FILE_PATH, 'rb') as f:
files = {'file': f}
data = {
'repo_id': REPO_ID,
'token': HF_TOKEN,
'subfolder': 'datasets'
}
print('π€ Uploading file...')
response = requests.post(
API_URL,
files=files,
data=data,
timeout=30
)
# Check response
if response.status_code == 200:
result = response.json()
print('β
Upload berhasil!')
print('π Response:')
import json
print(json.dumps(result, indent=2))
return result
else:
print(f'β Error {response.status_code}:')
print(response.json())
sys.exit(1)
except requests.exceptions.ConnectionError:
print('β Tidak dapat connect ke API')
print(f' Pastikan server berjalan di {API_URL}')
sys.exit(1)
except Exception as e:
print(f'β Error: {str(e)}')
sys.exit(1)
if __name__ == '__main__':
upload_file()
|