cronjob / app.py
testdeep123's picture
Update app.py
56a75e7 verified
raw
history blame
2.03 kB
import os
from flask import Flask, request, send_file, redirect, url_for, render_template_string
from huggingface_hub import HfApi, upload_file
import tempfile
# Get credentials from environment
REPO_ID = os.getenv("REPO_ID")
TOKEN = os.getenv("HF_TOKEN")
app = Flask(__name__)
api = HfApi()
# Basic HTML template with upload form
TEMPLATE = """
<!doctype html>
<title>Hugging Face Dataset Browser</title>
<h2>Files in {{ repo_id }}</h2>
<ul>
{% for file in files %}
<li>
{{ file }} —
<a href="{{ url_for('download_file', filename=file) }}">Download</a>
</li>
{% endfor %}
</ul>
<h3>Upload File</h3>
<form method="POST" action="/upload" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="Upload">
</form>
"""
@app.route("/")
def index():
files = api.list_repo_files(repo_id=REPO_ID, repo_type="dataset", token=TOKEN)
return render_template_string(TEMPLATE, files=files, repo_id=REPO_ID)
@app.route("/download/<path:filename>")
def download_file(filename):
url = api.hf_hub_url(REPO_ID, filename, repo_type="dataset")
import requests
headers = {"Authorization": f"Bearer {TOKEN}"}
r = requests.get(url, headers=headers)
if r.status_code == 200:
tmp = tempfile.NamedTemporaryFile(delete=False)
tmp.write(r.content)
tmp.close()
return send_file(tmp.name, as_attachment=True, download_name=os.path.basename(filename))
else:
return f"Failed to download {filename}", 404
@app.route("/upload", methods=["POST"])
def upload():
file = request.files["file"]
if file:
temp_path = os.path.join(tempfile.gettempdir(), file.filename)
file.save(temp_path)
upload_file(
path_or_fileobj=temp_path,
path_in_repo=file.filename,
repo_id=REPO_ID,
repo_type="dataset",
token=TOKEN
)
return redirect(url_for("index"))
if __name__ == "__main__":
app.run(debug=True, host="0.0.0.0", port=7860)