Spaces:
Sleeping
Sleeping
import os | |
from fastapi import FastAPI, File, UploadFile, HTTPException | |
from firebase_admin import credentials, initialize_app, storage | |
from uuid import uuid4 | |
import json | |
# Khởi tạo FastAPI app | |
app = FastAPI() | |
# Đường dẫn đến file JSON chứa thông tin xác thực Firebase | |
firebase_creds = os.getenv("FIREBASE_CREDENTIALS") | |
cred_dict = json.loads(firebase_creds) | |
cred = credentials.Certificate(cred_dict) | |
initialize_app(cred, { | |
'storageBucket': 'trans-paper.appspot.com' | |
}) | |
# Cấu hình thư mục tạm thời để lưu file trước khi tải lên Firebase | |
UPLOAD_FOLDER = 'uploads' | |
if not os.path.exists(UPLOAD_FOLDER): | |
os.makedirs(UPLOAD_FOLDER) | |
# Hàm để upload file lên Firebase | |
def upload_file_to_firebase(file_path: str, filename: str): | |
bucket = storage.bucket() | |
blob = bucket.blob(filename) | |
blob.upload_from_filename(file_path) | |
blob.make_public() # Tạo đường dẫn công khai | |
return blob.public_url | |
# API cho phép user tải ảnh lên | |
async def upload_image(file: UploadFile = File(...)): | |
try: | |
file_name = f"{uuid4()}_{file.filename}" | |
file_path = f"uploads/{file_name}" | |
# Lưu file tạm vào thư mục | |
with open(file_path, "wb") as buffer: | |
buffer.write(await file.read()) | |
# Upload file lên Firebase | |
public_url = upload_file_to_firebase(file_path, file_name) | |
# Xóa file tạm sau khi upload | |
if os.path.exists(file_path): | |
os.remove(file_path) | |
return {"message": "File uploaded successfully", "url": public_url} | |
except Exception as e: | |
# In ra thông báo lỗi chi tiết | |
print(f"Error: {str(e)}") | |
raise HTTPException(status_code=500, detail=f"Upload failed: {str(e)}") | |
# Chạy ứng dụng với Uvicorn | |
if __name__ == "__main__": | |
import uvicorn | |
uvicorn.run(app, host="0.0.0.0", port=8000) | |