Upload api_server/utils/file_operations.py with huggingface_hub
Browse files
api_server/utils/file_operations.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from typing import List, Union, TypedDict, Literal
|
| 3 |
+
from typing_extensions import TypeGuard
|
| 4 |
+
class FileInfo(TypedDict):
|
| 5 |
+
name: str
|
| 6 |
+
path: str
|
| 7 |
+
type: Literal["file"]
|
| 8 |
+
size: int
|
| 9 |
+
|
| 10 |
+
class DirectoryInfo(TypedDict):
|
| 11 |
+
name: str
|
| 12 |
+
path: str
|
| 13 |
+
type: Literal["directory"]
|
| 14 |
+
|
| 15 |
+
FileSystemItem = Union[FileInfo, DirectoryInfo]
|
| 16 |
+
|
| 17 |
+
def is_file_info(item: FileSystemItem) -> TypeGuard[FileInfo]:
|
| 18 |
+
return item["type"] == "file"
|
| 19 |
+
|
| 20 |
+
class FileSystemOperations:
|
| 21 |
+
@staticmethod
|
| 22 |
+
def walk_directory(directory: str) -> List[FileSystemItem]:
|
| 23 |
+
file_list: List[FileSystemItem] = []
|
| 24 |
+
for root, dirs, files in os.walk(directory):
|
| 25 |
+
for name in files:
|
| 26 |
+
file_path = os.path.join(root, name)
|
| 27 |
+
relative_path = os.path.relpath(file_path, directory)
|
| 28 |
+
file_list.append({
|
| 29 |
+
"name": name,
|
| 30 |
+
"path": relative_path,
|
| 31 |
+
"type": "file",
|
| 32 |
+
"size": os.path.getsize(file_path)
|
| 33 |
+
})
|
| 34 |
+
for name in dirs:
|
| 35 |
+
dir_path = os.path.join(root, name)
|
| 36 |
+
relative_path = os.path.relpath(dir_path, directory)
|
| 37 |
+
file_list.append({
|
| 38 |
+
"name": name,
|
| 39 |
+
"path": relative_path,
|
| 40 |
+
"type": "directory"
|
| 41 |
+
})
|
| 42 |
+
return file_list
|