Spaces:
Sleeping
Sleeping
Upload 4 files
Browse files- Dockerfile +34 -0
- client.py +121 -0
- main.py +119 -0
- requirements.txt +4 -0
Dockerfile
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Use Python 3.10 slim image as base
|
| 2 |
+
FROM python:3.10-slim
|
| 3 |
+
|
| 4 |
+
# Create non-root user
|
| 5 |
+
RUN useradd -m -u 1000 user
|
| 6 |
+
|
| 7 |
+
# Set environment variables
|
| 8 |
+
ENV HOME=/home/user \
|
| 9 |
+
PATH=/home/user/.local/bin:$PATH \
|
| 10 |
+
PORT=7860
|
| 11 |
+
|
| 12 |
+
# Create and set working directory
|
| 13 |
+
WORKDIR $HOME/app
|
| 14 |
+
|
| 15 |
+
# Copy requirements first to leverage Docker cache
|
| 16 |
+
COPY --chown=user requirements.txt .
|
| 17 |
+
|
| 18 |
+
# Switch to non-root user
|
| 19 |
+
USER user
|
| 20 |
+
|
| 21 |
+
# Install dependencies
|
| 22 |
+
RUN pip install --user -r requirements.txt
|
| 23 |
+
|
| 24 |
+
# Copy application files
|
| 25 |
+
COPY --chown=user . .
|
| 26 |
+
|
| 27 |
+
# Create uploads directory
|
| 28 |
+
RUN mkdir -p uploads
|
| 29 |
+
|
| 30 |
+
# Expose port
|
| 31 |
+
EXPOSE ${PORT}
|
| 32 |
+
|
| 33 |
+
# Command to run the application
|
| 34 |
+
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860", "--reload"]
|
client.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import requests
|
| 2 |
+
import os
|
| 3 |
+
|
| 4 |
+
class FileServerClient:
|
| 5 |
+
def __init__(self, base_url="http://localhost:7860"):
|
| 6 |
+
self.base_url = base_url
|
| 7 |
+
self.access_codes = {} # Store filename to access code mapping
|
| 8 |
+
|
| 9 |
+
def upload_file(self, file_path):
|
| 10 |
+
"""Upload a single file to the server"""
|
| 11 |
+
if not os.path.exists(file_path):
|
| 12 |
+
print(f"Error: File {file_path} not found")
|
| 13 |
+
return
|
| 14 |
+
|
| 15 |
+
with open(file_path, 'rb') as f:
|
| 16 |
+
files = {'file': f}
|
| 17 |
+
response = requests.post(f"{self.base_url}/upload/", files=files)
|
| 18 |
+
result = response.json()
|
| 19 |
+
|
| 20 |
+
# Store the access code
|
| 21 |
+
if 'access_code' in result:
|
| 22 |
+
self.access_codes[os.path.basename(file_path)] = result['access_code']
|
| 23 |
+
|
| 24 |
+
return result
|
| 25 |
+
|
| 26 |
+
def upload_multiple_files(self, file_paths):
|
| 27 |
+
"""Upload multiple files to the server"""
|
| 28 |
+
files = []
|
| 29 |
+
for file_path in file_paths:
|
| 30 |
+
if os.path.exists(file_path):
|
| 31 |
+
files.append(('files', open(file_path, 'rb')))
|
| 32 |
+
else:
|
| 33 |
+
print(f"Warning: File {file_path} not found, skipping...")
|
| 34 |
+
|
| 35 |
+
response = requests.post(f"{self.base_url}/upload-multiple/", files=files)
|
| 36 |
+
result = response.json()
|
| 37 |
+
|
| 38 |
+
# Store access codes
|
| 39 |
+
if 'files' in result:
|
| 40 |
+
for file_info in result['files']:
|
| 41 |
+
self.access_codes[file_info['filename']] = file_info['access_code']
|
| 42 |
+
|
| 43 |
+
# Close all opened files
|
| 44 |
+
for _, file_obj in files:
|
| 45 |
+
file_obj.close()
|
| 46 |
+
|
| 47 |
+
return result
|
| 48 |
+
|
| 49 |
+
def list_files(self):
|
| 50 |
+
"""List all files on the server"""
|
| 51 |
+
response = requests.get(f"{self.base_url}/files/")
|
| 52 |
+
return response.json()
|
| 53 |
+
|
| 54 |
+
def download_file(self, access_code, save_path):
|
| 55 |
+
"""Download a file using its access code"""
|
| 56 |
+
response = requests.get(f"{self.base_url}/download/{access_code}", stream=True)
|
| 57 |
+
|
| 58 |
+
if response.status_code == 200:
|
| 59 |
+
with open(save_path, 'wb') as f:
|
| 60 |
+
for chunk in response.iter_content(chunk_size=8192):
|
| 61 |
+
f.write(chunk)
|
| 62 |
+
return True
|
| 63 |
+
else:
|
| 64 |
+
print(f"Error: {response.json()['detail']}")
|
| 65 |
+
return False
|
| 66 |
+
|
| 67 |
+
def delete_file(self, access_code):
|
| 68 |
+
"""Delete a file using its access code"""
|
| 69 |
+
response = requests.delete(f"{self.base_url}/delete/{access_code}")
|
| 70 |
+
return response.json()
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def main():
|
| 74 |
+
# Create client instance
|
| 75 |
+
client = FileServerClient()
|
| 76 |
+
|
| 77 |
+
print("\n=== File Server Client Demo ===\n")
|
| 78 |
+
|
| 79 |
+
# 1. Upload a single file
|
| 80 |
+
print("1. Testing single file upload:")
|
| 81 |
+
test_file = "test_upload.txt"
|
| 82 |
+
with open(test_file, "w") as f:
|
| 83 |
+
f.write("This is a test file for upload!")
|
| 84 |
+
|
| 85 |
+
result = client.upload_file(test_file)
|
| 86 |
+
print(result)
|
| 87 |
+
access_code = result['access_code']
|
| 88 |
+
|
| 89 |
+
# 2. List files
|
| 90 |
+
print("\n2. Listing all files on server:")
|
| 91 |
+
files = client.list_files()
|
| 92 |
+
print(files)
|
| 93 |
+
|
| 94 |
+
# 3. Download the file using access code
|
| 95 |
+
print("\n3. Downloading the file:")
|
| 96 |
+
download_path = "downloaded_test.txt"
|
| 97 |
+
success = client.download_file(access_code, download_path)
|
| 98 |
+
if success:
|
| 99 |
+
print(f"File downloaded successfully to {download_path}")
|
| 100 |
+
|
| 101 |
+
# 4. Upload multiple files
|
| 102 |
+
print("\n4. Testing multiple file upload:")
|
| 103 |
+
test_file2 = "test_upload2.txt"
|
| 104 |
+
with open(test_file2, "w") as f:
|
| 105 |
+
f.write("This is another test file!")
|
| 106 |
+
|
| 107 |
+
result = client.upload_multiple_files([test_file, test_file2])
|
| 108 |
+
print(result)
|
| 109 |
+
|
| 110 |
+
# 5. Delete files using access codes
|
| 111 |
+
print("\n5. Deleting test files from server:")
|
| 112 |
+
for file_info in result['files']:
|
| 113 |
+
print(client.delete_file(file_info['access_code']))
|
| 114 |
+
|
| 115 |
+
# Clean up local test files
|
| 116 |
+
os.remove(test_file)
|
| 117 |
+
os.remove(test_file2)
|
| 118 |
+
os.remove(download_path)
|
| 119 |
+
|
| 120 |
+
if __name__ == "__main__":
|
| 121 |
+
main()
|
main.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, UploadFile, File, HTTPException
|
| 2 |
+
from fastapi.responses import FileResponse
|
| 3 |
+
from typing import List, Dict
|
| 4 |
+
import os
|
| 5 |
+
import shutil
|
| 6 |
+
import uuid
|
| 7 |
+
|
| 8 |
+
app = FastAPI()
|
| 9 |
+
|
| 10 |
+
# Create uploads directory if it doesn't exist
|
| 11 |
+
UPLOAD_DIR = "uploads"
|
| 12 |
+
if not os.path.exists(UPLOAD_DIR):
|
| 13 |
+
os.makedirs(UPLOAD_DIR)
|
| 14 |
+
|
| 15 |
+
# Store file mappings: {unique_code: filename}
|
| 16 |
+
file_codes: Dict[str, str] = {}
|
| 17 |
+
# Reverse mapping for easy lookup: {filename: unique_code}
|
| 18 |
+
filename_codes: Dict[str, str] = {}
|
| 19 |
+
|
| 20 |
+
@app.post("/upload/")
|
| 21 |
+
async def upload_file(file: UploadFile = File(...)):
|
| 22 |
+
try:
|
| 23 |
+
# Generate unique code
|
| 24 |
+
unique_code = str(uuid.uuid4())[:8]
|
| 25 |
+
|
| 26 |
+
# Save the uploaded file
|
| 27 |
+
file_path = os.path.join(UPLOAD_DIR, file.filename)
|
| 28 |
+
with open(file_path, "wb") as buffer:
|
| 29 |
+
shutil.copyfileobj(file.file, buffer)
|
| 30 |
+
|
| 31 |
+
# Store the mapping
|
| 32 |
+
file_codes[unique_code] = file.filename
|
| 33 |
+
filename_codes[file.filename] = unique_code
|
| 34 |
+
|
| 35 |
+
return {
|
| 36 |
+
"filename": file.filename,
|
| 37 |
+
"access_code": unique_code,
|
| 38 |
+
"message": "File uploaded successfully"
|
| 39 |
+
}
|
| 40 |
+
except Exception as e:
|
| 41 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 42 |
+
|
| 43 |
+
@app.post("/upload-multiple/")
|
| 44 |
+
async def upload_multiple_files(files: List[UploadFile] = File(...)):
|
| 45 |
+
try:
|
| 46 |
+
uploaded_files = []
|
| 47 |
+
for file in files:
|
| 48 |
+
# Generate unique code for each file
|
| 49 |
+
unique_code = str(uuid.uuid4())[:8]
|
| 50 |
+
|
| 51 |
+
file_path = os.path.join(UPLOAD_DIR, file.filename)
|
| 52 |
+
with open(file_path, "wb") as buffer:
|
| 53 |
+
shutil.copyfileobj(file.file, buffer)
|
| 54 |
+
|
| 55 |
+
# Store the mapping
|
| 56 |
+
file_codes[unique_code] = file.filename
|
| 57 |
+
filename_codes[file.filename] = unique_code
|
| 58 |
+
|
| 59 |
+
uploaded_files.append({
|
| 60 |
+
"filename": file.filename,
|
| 61 |
+
"access_code": unique_code
|
| 62 |
+
})
|
| 63 |
+
return {"files": uploaded_files, "message": "Files uploaded successfully"}
|
| 64 |
+
except Exception as e:
|
| 65 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 66 |
+
|
| 67 |
+
@app.get("/files/")
|
| 68 |
+
async def list_files():
|
| 69 |
+
try:
|
| 70 |
+
files = []
|
| 71 |
+
for filename in os.listdir(UPLOAD_DIR):
|
| 72 |
+
code = filename_codes.get(filename, "no_code")
|
| 73 |
+
files.append({
|
| 74 |
+
"filename": filename,
|
| 75 |
+
"access_code": code
|
| 76 |
+
})
|
| 77 |
+
return {"files": files}
|
| 78 |
+
except Exception as e:
|
| 79 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 80 |
+
|
| 81 |
+
@app.get("/download/{access_code}")
|
| 82 |
+
async def download_file(access_code: str):
|
| 83 |
+
try:
|
| 84 |
+
if access_code not in file_codes:
|
| 85 |
+
raise HTTPException(status_code=404, detail="Invalid access code")
|
| 86 |
+
|
| 87 |
+
filename = file_codes[access_code]
|
| 88 |
+
file_path = os.path.join(UPLOAD_DIR, filename)
|
| 89 |
+
|
| 90 |
+
if os.path.exists(file_path):
|
| 91 |
+
return FileResponse(file_path, filename=filename)
|
| 92 |
+
else:
|
| 93 |
+
raise HTTPException(status_code=404, detail="File not found")
|
| 94 |
+
except Exception as e:
|
| 95 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 96 |
+
|
| 97 |
+
@app.delete("/delete/{access_code}")
|
| 98 |
+
async def delete_file(access_code: str):
|
| 99 |
+
try:
|
| 100 |
+
if access_code not in file_codes:
|
| 101 |
+
raise HTTPException(status_code=404, detail="Invalid access code")
|
| 102 |
+
|
| 103 |
+
filename = file_codes[access_code]
|
| 104 |
+
file_path = os.path.join(UPLOAD_DIR, filename)
|
| 105 |
+
|
| 106 |
+
if os.path.exists(file_path):
|
| 107 |
+
os.remove(file_path)
|
| 108 |
+
# Remove from both mappings
|
| 109 |
+
del filename_codes[filename]
|
| 110 |
+
del file_codes[access_code]
|
| 111 |
+
return {"message": f"File {filename} deleted successfully"}
|
| 112 |
+
else:
|
| 113 |
+
raise HTTPException(status_code=404, detail="File not found")
|
| 114 |
+
except Exception as e:
|
| 115 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 116 |
+
|
| 117 |
+
if __name__ == "__main__":
|
| 118 |
+
import uvicorn
|
| 119 |
+
uvicorn.run(app, host="0.0.0.0", port=7860)
|
requirements.txt
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
fastapi==0.104.1
|
| 2 |
+
python-multipart==0.0.6
|
| 3 |
+
uvicorn==0.24.0
|
| 4 |
+
requests==2.31.0
|