filefn 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,67 @@
1
+ # Dependencies
2
+ node_modules/
3
+ .pnp
4
+ .pnp.js
5
+
6
+ # Build outputs
7
+ dist/
8
+ build/
9
+ *.tsbuildinfo
10
+
11
+ # TypeScript compiled outputs in src/tests
12
+ **/*.js
13
+ **/*.d.ts
14
+ **/*.d.ts.map
15
+ # But allow config files
16
+ !*.config.js
17
+ !**/vitest.config.js
18
+ !**/tsup.config.js
19
+
20
+ # Logs
21
+ logs
22
+ *.log
23
+ npm-debug.log*
24
+ yarn-debug.log*
25
+ yarn-error.log*
26
+ lerna-debug.log*
27
+ .pnpm-debug.log*
28
+
29
+ # Environment variables
30
+ .env
31
+ .env.*
32
+ !.env.example
33
+
34
+ # Security
35
+ *.pem
36
+ *.p12
37
+ *.key
38
+ *-key.pem
39
+
40
+ # Testing
41
+ coverage/
42
+ .nyc_output
43
+
44
+ # Editors
45
+ .vscode/
46
+ .idea/
47
+ *.swp
48
+ *.swo
49
+ *~
50
+ .DS_Store
51
+
52
+ # Turbo
53
+ .turbo/
54
+
55
+ # Misc
56
+ *.tgz
57
+ .cache/
58
+ *.bundled_*.mjs
59
+
60
+
61
+ _conduct/.meta
62
+
63
+ .agent
64
+ .venv
65
+
66
+ __pycache__
67
+ venv
filefn-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,203 @@
1
+ Metadata-Version: 2.4
2
+ Name: filefn
3
+ Version: 0.1.0
4
+ Summary: FileFn SDK for Python - File upload, storage, and processing
5
+ Project-URL: Documentation, https://docs.superfunctions.dev/filefn
6
+ Project-URL: Repository, https://github.com/21nCo/super-functions
7
+ Project-URL: Issues, https://github.com/21nCo/super-functions/issues
8
+ Author: 21n
9
+ License-Expression: MIT
10
+ Keywords: file,processing,storage,superfunctions,upload
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
19
+ Requires-Python: >=3.10
20
+ Requires-Dist: pillow>=10.0.0
21
+ Requires-Dist: pydantic>=2.5.0
22
+ Requires-Dist: superfunctions>=0.1.0
23
+ Provides-Extra: dev
24
+ Requires-Dist: black>=23.11.0; extra == 'dev'
25
+ Requires-Dist: mypy>=1.7.0; extra == 'dev'
26
+ Requires-Dist: pytest-asyncio>=0.21.0; extra == 'dev'
27
+ Requires-Dist: pytest-cov>=4.1.0; extra == 'dev'
28
+ Requires-Dist: pytest>=7.4.0; extra == 'dev'
29
+ Requires-Dist: ruff>=0.1.6; extra == 'dev'
30
+ Description-Content-Type: text/markdown
31
+
32
+ # FileFn Python SDK
33
+
34
+ The **FileFn Python SDK** is a powerful library for implementing robust file management capabilities in your Python applications. It provides a complete "backend-in-a-box" for handling file uploads, storage abstraction, metadata management, processing pipelines (like image thumbnails), and secure sharing.
35
+
36
+ Designed to integrate seamlessly with the [Superfunctions](https://github.com/21nCo/super-functions) ecosystem, it delegates persistence and storage to pluggable adapters.
37
+
38
+ ## Features
39
+
40
+ - **Chunked & Resumable Uploads:** Built-in support for creating upload sessions, handling multi-part uploads, and verifying completion.
41
+ - **Storage Abstraction:** Works with any `StorageAdapter` (S3, GCS, Azure, Local, etc.) provided by Superfunctions.
42
+ - **File Processing:** Extensible processing pipeline. Includes a built-in **Thumbnail Processor** for on-the-fly image resizing.
43
+ - **Deduplication:** Optional content-addressable storage logic to avoid storing duplicate files.
44
+ - **Security & Permissions:**
45
+ - **Signed URLs:** Secure upload and download links.
46
+ - **Grants System:** Fine-grained permissions (read/write/delete/share) for users/tenants.
47
+ - **Policies:** Define storage and access policies.
48
+ - **Sharing:** Generate secure, expiring share links for public or restricted access.
49
+ - **Observability:** Built-in event emitter for tracking file operations.
50
+
51
+ ## Installation
52
+
53
+ ```bash
54
+ pip install filefn
55
+ ```
56
+
57
+ ## Quick Start
58
+
59
+ The core of the library is the `FileFn` class, initialized via `create_file_fn`. You need to provide database and storage adapters.
60
+
61
+ ### 1. Setup & Initialization
62
+
63
+ ```python
64
+ import asyncio
65
+ from filefn.server import create_file_fn, FileFnConfig
66
+ from filefn.processing.processors.thumbnail import create_thumbnail_processor, ThumbnailConfig
67
+
68
+ # Import adapters from your specific implementation or mocks
69
+ # from superfunctions.db.memory import MemoryAdapter
70
+ # from superfunctions.storage.local import LocalStorageAdapter
71
+
72
+ async def main():
73
+ # 1. Initialize Adapters (Examples)
74
+ # db_adapter = MemoryAdapter()
75
+ # storage_adapter = LocalStorageAdapter(root_dir="./tmp_storage")
76
+
77
+ # 2. Configure FileFn
78
+ config = FileFnConfig(
79
+ db=db_adapter,
80
+ storage=storage_adapter,
81
+ namespace="my-app-files",
82
+
83
+ # Optional: Enable image thumbnail generation
84
+ processing={
85
+ "enabled": True,
86
+ "processors": [
87
+ create_thumbnail_processor(ThumbnailConfig(
88
+ format="jpeg",
89
+ quality=80,
90
+ sizes=[
91
+ {"name": "thumb", "width": 150, "height": 150},
92
+ {"name": "preview", "width": 800, "height": 600}
93
+ ]
94
+ ))
95
+ ]
96
+ },
97
+
98
+ # Security settings
99
+ signed_url_ttl_seconds=3600, # 1 hour
100
+ )
101
+
102
+ # 3. Create the Service
103
+ filefn = create_file_fn(config)
104
+
105
+ # Now you can use filefn to manage files
106
+ print("FileFn Service initialized!")
107
+
108
+ if __name__ == "__main__":
109
+ asyncio.run(main())
110
+ ```
111
+
112
+ ### 2. Handling Uploads
113
+
114
+ FileFn uses a session-based approach for uploads (similar to S3 Multipart Uploads) to handle large files reliably.
115
+
116
+ ```python
117
+ # 1. Create an Upload Session
118
+ session_input = {
119
+ "fileName": "vacation_photo.jpg",
120
+ "mimeType": "image/jpeg",
121
+ "size": 1024 * 1024 * 5, # 5MB
122
+ "ownerId": "user_123",
123
+ "policy": "default"
124
+ }
125
+ # ctx is a context object, usually containing request/auth info
126
+ ctx = {}
127
+ session = await filefn.create_upload_session(session_input, ctx)
128
+ print(f"Session created: {session['uploadSessionId']}")
129
+
130
+ # 2. Client uploads parts using signed URLs provided in the session...
131
+ # (The client would PUT data to session['parts'][0]['url'], etc.)
132
+
133
+ # 3. Complete the Session (after client finishes uploading)
134
+ await filefn.complete_upload_session({
135
+ "uploadSessionId": session['uploadSessionId']
136
+ }, ctx)
137
+
138
+ print("Upload complete & file created!")
139
+ ```
140
+
141
+ ### 3. Listing & Downloading
142
+
143
+ ```python
144
+ # List files for a specific owner
145
+ files = await filefn.list_files({
146
+ "ownerId": "user_123",
147
+ "limit": 20
148
+ }, ctx)
149
+
150
+ for f in files['items']:
151
+ print(f"File: {f['name']} ({f['size']} bytes)")
152
+
153
+ # Get a download URL (Signed URL)
154
+ file_data = await filefn.get_file({"fileId": files['items'][0]['fileId']}, ctx)
155
+ print(f"Download URL: {file_data['downloadUrl']}")
156
+ ```
157
+
158
+ ## Configuration Options
159
+
160
+ The `FileFnConfig` model accepts the following parameters:
161
+
162
+ | Parameter | Type | Description |
163
+ |-----------|------|-------------|
164
+ | `db` | `Adapter` | **Required.** Database adapter instance. |
165
+ | `storage` | `StorageAdapter` | **Required.** Storage adapter instance. |
166
+ | `namespace` | `str` | Table prefix for database (default: `'filefn'`). |
167
+ | `policies` | `List[Policy]` | Custom storage/access policies. |
168
+ | `processing` | `Dict` | Configuration for file processing (thumbnails, etc.). |
169
+ | `authorizer` | `Authorizer` | Optional custom authorization logic. |
170
+ | `quota` | `QuotaProvider` | Optional quota management provider. |
171
+ | `signed_url_ttl_seconds` | `int` | TTL for generated signed URLs (default: `900`). |
172
+ | `upload_session_ttl_seconds` | `int` | TTL for pending upload sessions (default: `86400`). |
173
+
174
+ ## Processors
175
+
176
+ ### Thumbnail Processor
177
+
178
+ Automatically generates image thumbnails upon upload completion.
179
+
180
+ ```python
181
+ from filefn.processing.processors.thumbnail import create_thumbnail_processor, ThumbnailConfig
182
+
183
+ processor = create_thumbnail_processor(ThumbnailConfig(
184
+ sizes=[
185
+ {"name": "small", "width": 100, "height": 100},
186
+ {"name": "large", "width": 1024, "height": 1024}
187
+ ],
188
+ format="webp", # 'jpeg', 'png', 'webp'
189
+ quality=90
190
+ ))
191
+ ```
192
+
193
+ ## Architecture
194
+
195
+ FileFn is built on a modular architecture:
196
+
197
+ - **Core Service (`FileFn`):** Orchestrates all operations.
198
+ - **UploadSessionService:** Manages the lifecycle of multipart uploads.
199
+ - **FileService:** Handles file metadata (indexing, searching) and deletion.
200
+ - **ProcessingService:** Runs background jobs (processors) on new files.
201
+ - **Adapters:** Decouples the logic from specific infrastructure (DB/Storage).
202
+
203
+ This design allows FileFn to run on your local machine, in a serverless function, or a dedicated container with equal ease.
filefn-0.1.0/README.md ADDED
@@ -0,0 +1,172 @@
1
+ # FileFn Python SDK
2
+
3
+ The **FileFn Python SDK** is a powerful library for implementing robust file management capabilities in your Python applications. It provides a complete "backend-in-a-box" for handling file uploads, storage abstraction, metadata management, processing pipelines (like image thumbnails), and secure sharing.
4
+
5
+ Designed to integrate seamlessly with the [Superfunctions](https://github.com/21nCo/super-functions) ecosystem, it delegates persistence and storage to pluggable adapters.
6
+
7
+ ## Features
8
+
9
+ - **Chunked & Resumable Uploads:** Built-in support for creating upload sessions, handling multi-part uploads, and verifying completion.
10
+ - **Storage Abstraction:** Works with any `StorageAdapter` (S3, GCS, Azure, Local, etc.) provided by Superfunctions.
11
+ - **File Processing:** Extensible processing pipeline. Includes a built-in **Thumbnail Processor** for on-the-fly image resizing.
12
+ - **Deduplication:** Optional content-addressable storage logic to avoid storing duplicate files.
13
+ - **Security & Permissions:**
14
+ - **Signed URLs:** Secure upload and download links.
15
+ - **Grants System:** Fine-grained permissions (read/write/delete/share) for users/tenants.
16
+ - **Policies:** Define storage and access policies.
17
+ - **Sharing:** Generate secure, expiring share links for public or restricted access.
18
+ - **Observability:** Built-in event emitter for tracking file operations.
19
+
20
+ ## Installation
21
+
22
+ ```bash
23
+ pip install filefn
24
+ ```
25
+
26
+ ## Quick Start
27
+
28
+ The core of the library is the `FileFn` class, initialized via `create_file_fn`. You need to provide database and storage adapters.
29
+
30
+ ### 1. Setup & Initialization
31
+
32
+ ```python
33
+ import asyncio
34
+ from filefn.server import create_file_fn, FileFnConfig
35
+ from filefn.processing.processors.thumbnail import create_thumbnail_processor, ThumbnailConfig
36
+
37
+ # Import adapters from your specific implementation or mocks
38
+ # from superfunctions.db.memory import MemoryAdapter
39
+ # from superfunctions.storage.local import LocalStorageAdapter
40
+
41
+ async def main():
42
+ # 1. Initialize Adapters (Examples)
43
+ # db_adapter = MemoryAdapter()
44
+ # storage_adapter = LocalStorageAdapter(root_dir="./tmp_storage")
45
+
46
+ # 2. Configure FileFn
47
+ config = FileFnConfig(
48
+ db=db_adapter,
49
+ storage=storage_adapter,
50
+ namespace="my-app-files",
51
+
52
+ # Optional: Enable image thumbnail generation
53
+ processing={
54
+ "enabled": True,
55
+ "processors": [
56
+ create_thumbnail_processor(ThumbnailConfig(
57
+ format="jpeg",
58
+ quality=80,
59
+ sizes=[
60
+ {"name": "thumb", "width": 150, "height": 150},
61
+ {"name": "preview", "width": 800, "height": 600}
62
+ ]
63
+ ))
64
+ ]
65
+ },
66
+
67
+ # Security settings
68
+ signed_url_ttl_seconds=3600, # 1 hour
69
+ )
70
+
71
+ # 3. Create the Service
72
+ filefn = create_file_fn(config)
73
+
74
+ # Now you can use filefn to manage files
75
+ print("FileFn Service initialized!")
76
+
77
+ if __name__ == "__main__":
78
+ asyncio.run(main())
79
+ ```
80
+
81
+ ### 2. Handling Uploads
82
+
83
+ FileFn uses a session-based approach for uploads (similar to S3 Multipart Uploads) to handle large files reliably.
84
+
85
+ ```python
86
+ # 1. Create an Upload Session
87
+ session_input = {
88
+ "fileName": "vacation_photo.jpg",
89
+ "mimeType": "image/jpeg",
90
+ "size": 1024 * 1024 * 5, # 5MB
91
+ "ownerId": "user_123",
92
+ "policy": "default"
93
+ }
94
+ # ctx is a context object, usually containing request/auth info
95
+ ctx = {}
96
+ session = await filefn.create_upload_session(session_input, ctx)
97
+ print(f"Session created: {session['uploadSessionId']}")
98
+
99
+ # 2. Client uploads parts using signed URLs provided in the session...
100
+ # (The client would PUT data to session['parts'][0]['url'], etc.)
101
+
102
+ # 3. Complete the Session (after client finishes uploading)
103
+ await filefn.complete_upload_session({
104
+ "uploadSessionId": session['uploadSessionId']
105
+ }, ctx)
106
+
107
+ print("Upload complete & file created!")
108
+ ```
109
+
110
+ ### 3. Listing & Downloading
111
+
112
+ ```python
113
+ # List files for a specific owner
114
+ files = await filefn.list_files({
115
+ "ownerId": "user_123",
116
+ "limit": 20
117
+ }, ctx)
118
+
119
+ for f in files['items']:
120
+ print(f"File: {f['name']} ({f['size']} bytes)")
121
+
122
+ # Get a download URL (Signed URL)
123
+ file_data = await filefn.get_file({"fileId": files['items'][0]['fileId']}, ctx)
124
+ print(f"Download URL: {file_data['downloadUrl']}")
125
+ ```
126
+
127
+ ## Configuration Options
128
+
129
+ The `FileFnConfig` model accepts the following parameters:
130
+
131
+ | Parameter | Type | Description |
132
+ |-----------|------|-------------|
133
+ | `db` | `Adapter` | **Required.** Database adapter instance. |
134
+ | `storage` | `StorageAdapter` | **Required.** Storage adapter instance. |
135
+ | `namespace` | `str` | Table prefix for database (default: `'filefn'`). |
136
+ | `policies` | `List[Policy]` | Custom storage/access policies. |
137
+ | `processing` | `Dict` | Configuration for file processing (thumbnails, etc.). |
138
+ | `authorizer` | `Authorizer` | Optional custom authorization logic. |
139
+ | `quota` | `QuotaProvider` | Optional quota management provider. |
140
+ | `signed_url_ttl_seconds` | `int` | TTL for generated signed URLs (default: `900`). |
141
+ | `upload_session_ttl_seconds` | `int` | TTL for pending upload sessions (default: `86400`). |
142
+
143
+ ## Processors
144
+
145
+ ### Thumbnail Processor
146
+
147
+ Automatically generates image thumbnails upon upload completion.
148
+
149
+ ```python
150
+ from filefn.processing.processors.thumbnail import create_thumbnail_processor, ThumbnailConfig
151
+
152
+ processor = create_thumbnail_processor(ThumbnailConfig(
153
+ sizes=[
154
+ {"name": "small", "width": 100, "height": 100},
155
+ {"name": "large", "width": 1024, "height": 1024}
156
+ ],
157
+ format="webp", # 'jpeg', 'png', 'webp'
158
+ quality=90
159
+ ))
160
+ ```
161
+
162
+ ## Architecture
163
+
164
+ FileFn is built on a modular architecture:
165
+
166
+ - **Core Service (`FileFn`):** Orchestrates all operations.
167
+ - **UploadSessionService:** Manages the lifecycle of multipart uploads.
168
+ - **FileService:** Handles file metadata (indexing, searching) and deletion.
169
+ - **ProcessingService:** Runs background jobs (processors) on new files.
170
+ - **Adapters:** Decouples the logic from specific infrastructure (DB/Storage).
171
+
172
+ This design allows FileFn to run on your local machine, in a serverless function, or a dedicated container with equal ease.
@@ -0,0 +1 @@
1
+ # FileFn Python SDK
@@ -0,0 +1,25 @@
1
+ from .types import (
2
+ Processor,
3
+ ProcessorInput,
4
+ ProcessorOutputArtifact,
5
+ ProcessorResult,
6
+ ThumbnailConfig,
7
+ ThumbnailSize,
8
+ CompressionConfig,
9
+ OCRConfig,
10
+ ImageTransformOperation,
11
+ ImageTransformConfig,
12
+ ResizeOptions,
13
+ CropOptions,
14
+ RotateOptions
15
+ )
16
+
17
+ from .processors.thumbnail import (
18
+ create_thumbnail_processor,
19
+ THUMBNAIL_SUPPORTED_MIME_TYPES
20
+ )
21
+
22
+ from .processors.compression import (
23
+ create_compression_processor,
24
+ COMPRESSION_SUPPORTED_MIME_TYPES
25
+ )
@@ -0,0 +1,51 @@
1
+ import gzip
2
+ import io
3
+ from typing import Any, Optional, List
4
+ from ..types import Processor, ProcessorInput, ProcessorResult, ProcessorOutputArtifact, CompressionConfig
5
+
6
+ SUPPORTED_MIME_TYPES = ['*/*']
7
+
8
+ class CompressionProcessor:
9
+ def __init__(self, config: Optional[CompressionConfig] = None):
10
+ config = config or CompressionConfig()
11
+ self.algorithm = config.algorithm or 'gzip'
12
+ self.level = config.level or 6
13
+ self.name = 'compression'
14
+ self.supportedMimeTypes = SUPPORTED_MIME_TYPES
15
+
16
+ async def process(self, input: ProcessorInput, get_data: Any) -> ProcessorResult:
17
+ if self.algorithm != 'gzip':
18
+ return ProcessorResult(success=False, artifacts=[], error=f"Unsupported algorithm: {self.algorithm}")
19
+
20
+ try:
21
+ data = await get_data()
22
+
23
+ out_buffer = io.BytesIO()
24
+ with gzip.GzipFile(fileobj=out_buffer, mode='wb', compresslevel=self.level) as f:
25
+ f.write(data)
26
+
27
+ compressed_data = out_buffer.getvalue()
28
+
29
+ artifacts = [ProcessorOutputArtifact(
30
+ kind='compressed',
31
+ data=compressed_data,
32
+ mimeType='application/gzip',
33
+ storageKey=f"{input.storageKey}.gz",
34
+ metadata={
35
+ 'algorithm': self.algorithm,
36
+ 'level': self.level,
37
+ 'originalSize': len(data),
38
+ 'compressedSize': len(compressed_data),
39
+ 'ratio': len(compressed_data) / len(data) if len(data) > 0 else 0
40
+ }
41
+ )]
42
+
43
+ return ProcessorResult(success=True, artifacts=artifacts)
44
+
45
+ except Exception as e:
46
+ return ProcessorResult(success=False, artifacts=[], error=str(e))
47
+
48
+ def create_compression_processor(config: Optional[CompressionConfig] = None) -> Processor:
49
+ return CompressionProcessor(config)
50
+
51
+ COMPRESSION_SUPPORTED_MIME_TYPES = SUPPORTED_MIME_TYPES
@@ -0,0 +1,94 @@
1
+ import io
2
+ from typing import Any, List, Optional
3
+ from PIL import Image
4
+ from ..types import Processor, ProcessorInput, ProcessorResult, ProcessorOutputArtifact, ThumbnailConfig, ThumbnailSize
5
+
6
+ DEFAULT_SIZES = [
7
+ ThumbnailSize(name='small', width=150, height=150),
8
+ ThumbnailSize(name='medium', width=300, height=300),
9
+ ThumbnailSize(name='large', width=600, height=600),
10
+ ]
11
+
12
+ SUPPORTED_MIME_TYPES = ['image/png', 'image/jpeg', 'image/jpg', 'image/webp', 'image/gif', 'image/tiff']
13
+
14
+ class ThumbnailProcessor:
15
+ def __init__(self, config: Optional[ThumbnailConfig] = None):
16
+ config = config or ThumbnailConfig()
17
+ self.sizes = config.sizes or DEFAULT_SIZES
18
+ self.quality = config.quality or 80
19
+ self.format = config.format or 'jpeg'
20
+ self.name = 'thumbnail'
21
+ self.supportedMimeTypes = SUPPORTED_MIME_TYPES
22
+
23
+ async def process(self, input: ProcessorInput, get_data: Any) -> ProcessorResult:
24
+ if input.mimeType not in self.supportedMimeTypes:
25
+ return ProcessorResult(success=False, artifacts=[], error=f"Unsupported MIME type: {input.mimeType}")
26
+
27
+ try:
28
+ image_data = await get_data()
29
+ artifacts = []
30
+
31
+ for size in self.sizes:
32
+ thumbnail_data = self._generate_thumbnail(image_data, size)
33
+
34
+ output_mime_type = 'image/jpeg'
35
+ extension = 'jpg'
36
+ if self.format == 'png':
37
+ output_mime_type = 'image/png'
38
+ extension = 'png'
39
+ elif self.format == 'webp':
40
+ output_mime_type = 'image/webp'
41
+ extension = 'webp'
42
+
43
+ base_key = input.storageKey.rsplit('.', 1)[0]
44
+ storage_key = f"{base_key}-thumb-{size.name}.{extension}"
45
+
46
+ artifacts.append(ProcessorOutputArtifact(
47
+ kind=f"thumbnail-{size.name}",
48
+ data=thumbnail_data,
49
+ mimeType=output_mime_type,
50
+ storageKey=storage_key,
51
+ metadata={
52
+ 'width': size.width,
53
+ 'height': size.height,
54
+ 'quality': self.quality,
55
+ 'format': self.format,
56
+ 'sourceFileId': input.fileId,
57
+ 'sourceVersionId': input.versionId,
58
+ 'originalSize': len(image_data),
59
+ 'thumbnailSize': len(thumbnail_data)
60
+ }
61
+ ))
62
+
63
+ return ProcessorResult(success=True, artifacts=artifacts)
64
+
65
+ except Exception as e:
66
+ return ProcessorResult(success=False, artifacts=[], error=str(e))
67
+
68
+ def _generate_thumbnail(self, image_data: bytes, size: ThumbnailSize) -> bytes:
69
+ with io.BytesIO(image_data) as f:
70
+ with Image.open(f) as img:
71
+ img = img.copy() # Avoid issues with open files
72
+
73
+ # Convert to RGB if needed (e.g. RGBA to JPEG)
74
+ if self.format == 'jpeg' and img.mode in ('RGBA', 'P'):
75
+ img = img.convert('RGB')
76
+
77
+ img.thumbnail((size.width, size.height), Image.Resampling.LANCZOS)
78
+
79
+ out_buffer = io.BytesIO()
80
+ fmt = self.format.upper()
81
+ if fmt == 'JPG': fmt = 'JPEG'
82
+
83
+ save_args = {'format': fmt, 'quality': self.quality}
84
+ if fmt == 'PNG':
85
+ save_args['optimize'] = True
86
+ del save_args['quality'] # PNG uses compress_level but simple save is fine
87
+
88
+ img.save(out_buffer, **save_args)
89
+ return out_buffer.getvalue()
90
+
91
+ def create_thumbnail_processor(config: Optional[ThumbnailConfig] = None) -> Processor:
92
+ return ThumbnailProcessor(config)
93
+
94
+ THUMBNAIL_SUPPORTED_MIME_TYPES = SUPPORTED_MIME_TYPES
@@ -0,0 +1,73 @@
1
+ from typing import Any, Dict, List, Optional, Protocol, Union, Callable
2
+ from pydantic import BaseModel
3
+
4
+ class ProcessorInput(BaseModel):
5
+ fileId: str
6
+ versionId: str
7
+ storageKey: str
8
+ mimeType: str
9
+ size: int
10
+ fileName: str
11
+ tenantId: Optional[str] = None
12
+ metadata: Optional[Dict[str, Any]] = None
13
+
14
+ class ProcessorOutputArtifact(BaseModel):
15
+ kind: str
16
+ data: bytes
17
+ mimeType: str
18
+ storageKey: str
19
+ metadata: Optional[Dict[str, Any]] = None
20
+
21
+ class ProcessorResult(BaseModel):
22
+ success: bool
23
+ artifacts: List[ProcessorOutputArtifact]
24
+ error: Optional[str] = None
25
+
26
+ class Processor(Protocol):
27
+ name: str
28
+ supportedMimeTypes: List[str]
29
+ async def process(self, input: ProcessorInput, get_data: Callable[[], Any]) -> ProcessorResult: ...
30
+
31
+ class ThumbnailSize(BaseModel):
32
+ name: str
33
+ width: int
34
+ height: int
35
+
36
+ class ThumbnailConfig(BaseModel):
37
+ sizes: Optional[List[ThumbnailSize]] = None
38
+ quality: Optional[int] = 80
39
+ format: Optional[str] = 'jpeg' # 'jpeg' | 'png' | 'webp'
40
+
41
+ class CompressionConfig(BaseModel):
42
+ algorithm: Optional[str] = 'gzip'
43
+ level: Optional[int] = 6
44
+
45
+ class OCRConfig(BaseModel):
46
+ language: Optional[str] = 'eng'
47
+ outputFormat: Optional[str] = 'text'
48
+
49
+ class ResizeOptions(BaseModel):
50
+ width: Optional[int] = None
51
+ height: Optional[int] = None
52
+ fit: Optional[str] = 'cover' # 'cover' | 'contain' | 'fill' | 'inside' | 'outside'
53
+ withoutEnlargement: Optional[bool] = False
54
+
55
+ class CropOptions(BaseModel):
56
+ left: int
57
+ top: int
58
+ width: int
59
+ height: int
60
+
61
+ class RotateOptions(BaseModel):
62
+ angle: int
63
+ background: Optional[Dict[str, int]] = None # { r, g, b, alpha }
64
+
65
+ class ImageTransformOperation(BaseModel):
66
+ operation: str # 'resize' | 'crop' | 'rotate'
67
+ options: Union[ResizeOptions, CropOptions, RotateOptions]
68
+ suffix: Optional[str] = None
69
+
70
+ class ImageTransformConfig(BaseModel):
71
+ operations: List[ImageTransformOperation]
72
+ outputFormat: Optional[str] = None
73
+ outputQuality: Optional[int] = None