-
Notifications
You must be signed in to change notification settings - Fork 3
Add downloadable services and tasks file outputs #97
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
nikazzio
merged 12 commits into
brevia-ai:main
from
stefanorosanelli:feat/services-tasks-file-output
May 26, 2025
Merged
Changes from 4 commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
f08f559
feat: add file output with links support
stefanorosanelli 322bccb
feat: update PublicFileOutput + add service w file output
stefanorosanelli 7368967
tests: add test cases
stefanorosanelli 76bf460
chore: flake8
stefanorosanelli 7be6016
chore: pylint
stefanorosanelli 6bcb6a5
feat: use temp file for S3
stefanorosanelli eed135c
test: improve test + coverage
stefanorosanelli 0b9a79f
chore: copilot suggestion - use NamedTemporaryFile
stefanorosanelli 024aa4b
chore: env sample + git ignore
stefanorosanelli 58ccab7
refactor: rename class to LinkedFileOutput
stefanorosanelli d55c6d7
chore: flake8
stefanorosanelli 5614a50
chore: run tests on dependencies change
stefanorosanelli File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -34,3 +34,6 @@ brevia/extensions/* | |
|
|
||
| # docs site | ||
| site/ | ||
|
|
||
| # output folder | ||
| ./files/ | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,35 @@ | ||
| """Download files endpoint.""" | ||
| import os | ||
| from fastapi import APIRouter, HTTPException, status | ||
| from fastapi.responses import FileResponse | ||
| from brevia.settings import get_settings | ||
|
|
||
|
|
||
| router = APIRouter() | ||
|
|
||
|
|
||
| @router.api_route( | ||
| '/download/{file_path:path}', | ||
| methods=['GET', 'HEAD'], | ||
| tags=['Download'], | ||
| ) | ||
| async def download_file(file_path: str): | ||
| """ | ||
| Endpoint to download a file from the internal file system. | ||
| """ | ||
| base_path = get_settings().file_output_base_path | ||
| # Check if the base path is an S3 file path | ||
| if base_path.startswith('s3://'): | ||
| raise HTTPException( | ||
| status.HTTP_404_NOT_FOUND, | ||
| 'File download is not supported', | ||
| ) | ||
|
|
||
| full_path = os.path.join(base_path, file_path) | ||
| if not os.path.isfile(full_path): | ||
| raise HTTPException( | ||
| status.HTTP_404_NOT_FOUND, | ||
| f'File not found: {file_path}', | ||
| ) | ||
|
|
||
| return FileResponse(full_path, filename=os.path.basename(full_path)) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,91 @@ | ||
| import tempfile | ||
| import os | ||
| from brevia.settings import get_settings | ||
|
|
||
|
|
||
| class PublicFileOutput: | ||
| """ | ||
| A class to handle file output operations in Brevia that need a public link. | ||
| """ | ||
| job_id = None | ||
|
|
||
| def __init__(self, job_id: str = None): | ||
| """ | ||
| Initialize the FileOutput object with a job ID. | ||
| :param job_id: The job ID to associate with this output. | ||
| """ | ||
| self.job_id = job_id | ||
|
|
||
| def file_path(self, filename: str): | ||
| """ | ||
| Generate the file path for the output file. | ||
| :param filename: The name of the file. | ||
| :return: The full path to the file. | ||
| """ | ||
| base_path = get_settings().file_output_base_path | ||
| if base_path.startswith('s3://'): | ||
| out_dir = tempfile.mkdtemp() | ||
| if self.job_id: | ||
| out_dir = f"{base_path}/{self.job_id}" | ||
| os.makedirs(out_dir, exist_ok=True) | ||
| else: | ||
| out_dir = base_path | ||
|
|
||
| return f"{out_dir}/{filename}" | ||
|
|
||
| def file_url(self, filename: str): | ||
| """ | ||
| Generate the URL for the output file. | ||
| :param filename: The name of the file. | ||
| :return: The URL to access the file. | ||
| """ | ||
| # Generate the output URL | ||
| base_url = get_settings().file_output_base_url | ||
| return f'{base_url}/{filename}' | ||
|
|
||
| def _s3_upload(self, file_path: str, bucket_name: str, object_name: str): | ||
| """ | ||
| Upload the file to S3. | ||
| :param file_path: The path to the file to upload. | ||
| :param bucket_name: The name of the S3 bucket. | ||
| :param object_name: The S3 object name. | ||
| """ | ||
| try: | ||
| import boto3 # pylint: disable=import-outside-toplevel | ||
| s3 = boto3.client('s3') | ||
| return s3.upload_file(file_path, bucket_name, object_name) | ||
| except ImportError as exc: | ||
| raise ImportError('Boto3 is not installed!') from exc | ||
|
|
||
| def write(self, content: str, filename: str): | ||
| """ | ||
| Write content of the file to the specified filename. | ||
| Returns the URL of the file. | ||
| :param content: The content to write to the file. | ||
| :param filename: The name of the file to write to. | ||
| """ | ||
| output_path = self.file_path(filename) | ||
| with open(output_path, 'w', encoding='utf-8') as file: | ||
| file.write(content) | ||
|
|
||
| if self.job_id: | ||
| filename = f"{self.job_id}/{filename}" | ||
| base_path = get_settings().file_output_base_path | ||
| if base_path.startswith('s3://'): | ||
| # Extract bucket name and object name from S3 path | ||
| bucket_name = base_path.split('/')[2] | ||
| object_name = '/'.join(base_path.split('/')[3:]).lstrip('/') | ||
| object_name += f"/{filename}" | ||
stefanorosanelli marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| self._s3_upload(output_path, bucket_name, object_name.lstrip('/')) | ||
| # Remove the local file and its parent tmp directory | ||
| os.remove(output_path) | ||
| parent_dir = os.path.dirname(output_path) | ||
| if not os.listdir(parent_dir): | ||
| os.rmdir(parent_dir) | ||
|
|
||
| return self.file_url(filename) | ||
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| test |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,32 @@ | ||
| """Download Router module tests.""" | ||
| from unittest.mock import patch | ||
| from fastapi.testclient import TestClient | ||
| from fastapi import FastAPI, status | ||
| from brevia.routers.download_router import router | ||
|
|
||
| app = FastAPI() | ||
| app.include_router(router) | ||
| client = TestClient(app) | ||
|
|
||
|
|
||
| def test_download_file_success(): | ||
| """Test download file success.""" | ||
| response = client.get('/download/silence.mp3') | ||
| assert response.status_code == status.HTTP_200_OK | ||
|
|
||
|
|
||
| def test_download_file_not_found(): | ||
| """Test download file not found.""" | ||
| response = client.get('/download/nonexistent_file.txt') | ||
| assert response.status_code == status.HTTP_404_NOT_FOUND | ||
| assert response.json() == {'detail': 'File not found: nonexistent_file.txt'} | ||
|
|
||
|
|
||
| @patch('brevia.routers.download_router.get_settings') | ||
| def test_download_file_s3_path(mock_get_settings): | ||
| """Test download file from S3 path.""" | ||
| mock_get_settings.return_value.file_output_base_path = 's3://mock-bucket' | ||
|
|
||
| response = client.get('/download/test_file.txt') | ||
| assert response.status_code == status.HTTP_404_NOT_FOUND | ||
| assert response.json() == {'detail': 'File download is not supported'} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.