HLIT 0.0.1__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.
Files changed (67) hide show
  1. hlit-0.0.1/HLIT.egg-info/PKG-INFO +20 -0
  2. hlit-0.0.1/HLIT.egg-info/SOURCES.txt +65 -0
  3. hlit-0.0.1/HLIT.egg-info/dependency_links.txt +1 -0
  4. hlit-0.0.1/HLIT.egg-info/entry_points.txt +2 -0
  5. hlit-0.0.1/HLIT.egg-info/namespace_packages.txt +1 -0
  6. hlit-0.0.1/HLIT.egg-info/requires.txt +12 -0
  7. hlit-0.0.1/HLIT.egg-info/top_level.txt +1 -0
  8. hlit-0.0.1/License.txt +6 -0
  9. hlit-0.0.1/PKG-INFO +20 -0
  10. hlit-0.0.1/orangecontrib/OWInterface/__init__.py +0 -0
  11. hlit-0.0.1/orangecontrib/OWInterface/download/BaseLocalInterfaceWidget.py +88 -0
  12. hlit-0.0.1/orangecontrib/OWInterface/download/FileWatcher.py +17 -0
  13. hlit-0.0.1/orangecontrib/OWInterface/download/__init__.py +0 -0
  14. hlit-0.0.1/orangecontrib/OWInterface/webserver/__init__.py +0 -0
  15. hlit-0.0.1/orangecontrib/OWInterface/webserver/fileQueue.py +37 -0
  16. hlit-0.0.1/orangecontrib/OWInterface/webserver/main.py +270 -0
  17. hlit-0.0.1/orangecontrib/OWInterface/webserver/start_server.py +70 -0
  18. hlit-0.0.1/orangecontrib/OWInterface/webserver/utils.py +38 -0
  19. hlit-0.0.1/orangecontrib/OWInterface/widgets/OWDisplayOnInterface.py +127 -0
  20. hlit-0.0.1/orangecontrib/OWInterface/widgets/OWLocalInterface.py +45 -0
  21. hlit-0.0.1/orangecontrib/OWInterface/widgets/OWLocalInterfaceImages.py +82 -0
  22. hlit-0.0.1/orangecontrib/OWInterface/widgets/OWLocalInterfaceMultifile.py +66 -0
  23. hlit-0.0.1/orangecontrib/OWInterface/widgets/OWLocalInterfaceText.py +55 -0
  24. hlit-0.0.1/orangecontrib/OWInterface/widgets/__init__.py +0 -0
  25. hlit-0.0.1/orangecontrib/OWInterface/widgets/icons/MDViewer.png +0 -0
  26. hlit-0.0.1/orangecontrib/OWInterface/widgets/icons/Mistral.png +0 -0
  27. hlit-0.0.1/orangecontrib/OWInterface/widgets/icons/category.svg +50 -0
  28. hlit-0.0.1/orangecontrib/OWInterface/widgets/icons/dark_green.txt +1 -0
  29. hlit-0.0.1/orangecontrib/OWInterface/widgets/icons/documents.png +0 -0
  30. hlit-0.0.1/orangecontrib/OWInterface/widgets/icons/endloop.png +0 -0
  31. hlit-0.0.1/orangecontrib/OWInterface/widgets/icons/llm4all.svg +2 -0
  32. hlit-0.0.1/orangecontrib/OWInterface/widgets/icons/local_interf_img_multi_pull.svg +105 -0
  33. hlit-0.0.1/orangecontrib/OWInterface/widgets/icons/local_interf_multi_pull.svg +85 -0
  34. hlit-0.0.1/orangecontrib/OWInterface/widgets/icons/local_interf_pull.svg +52 -0
  35. hlit-0.0.1/orangecontrib/OWInterface/widgets/icons/local_interf_push.svg +79 -0
  36. hlit-0.0.1/orangecontrib/OWInterface/widgets/icons/local_interf_text_pull.svg +80 -0
  37. hlit-0.0.1/orangecontrib/OWInterface/widgets/icons/logo_solar.svg +101 -0
  38. hlit-0.0.1/orangecontrib/OWInterface/widgets/icons/logo_uncensoredsolar.svg +129 -0
  39. hlit-0.0.1/orangecontrib/OWInterface/widgets/icons/logo_upload.png +0 -0
  40. hlit-0.0.1/orangecontrib/OWInterface/widgets/icons/optimisation.png +0 -0
  41. hlit-0.0.1/orangecontrib/OWInterface/widgets/icons/owchunking.png +0 -0
  42. hlit-0.0.1/orangecontrib/OWInterface/widgets/icons/owedittable.svg +55 -0
  43. hlit-0.0.1/orangecontrib/OWInterface/widgets/icons/owembeddings.svg +3 -0
  44. hlit-0.0.1/orangecontrib/OWInterface/widgets/icons/owlemmatizer.svg +12 -0
  45. hlit-0.0.1/orangecontrib/OWInterface/widgets/icons/owmodel_helsinki_en_fr.svg +27 -0
  46. hlit-0.0.1/orangecontrib/OWInterface/widgets/icons/owmodel_helsinki_fr_en.svg +27 -0
  47. hlit-0.0.1/orangecontrib/OWInterface/widgets/icons/owmodel_mpnet.svg +27 -0
  48. hlit-0.0.1/orangecontrib/OWInterface/widgets/icons/owmodel_spacymd_fr.svg +27 -0
  49. hlit-0.0.1/orangecontrib/OWInterface/widgets/icons/owoptimisation.svg +7 -0
  50. hlit-0.0.1/orangecontrib/OWInterface/widgets/icons/owoptimisationselection.png +0 -0
  51. hlit-0.0.1/orangecontrib/OWInterface/widgets/icons/owqueryllm.svg +6 -0
  52. hlit-0.0.1/orangecontrib/OWInterface/widgets/icons/owtranslation.svg +1 -0
  53. hlit-0.0.1/orangecontrib/OWInterface/widgets/icons/qwen-color.png +0 -0
  54. hlit-0.0.1/orangecontrib/OWInterface/widgets/icons/startloop.png +0 -0
  55. hlit-0.0.1/orangecontrib/OWInterface/widgets/icons/widgetFactory.svg +170 -0
  56. hlit-0.0.1/setup.cfg +4 -0
  57. hlit-0.0.1/setup.py +61 -0
  58. hlit-0.0.1/tests/test_class_values_context_handler.py +75 -0
  59. hlit-0.0.1/tests/test_credentials.py +76 -0
  60. hlit-0.0.1/tests/test_domain_context_handler.py +401 -0
  61. hlit-0.0.1/tests/test_gui.py +140 -0
  62. hlit-0.0.1/tests/test_matplotlib_export.py +43 -0
  63. hlit-0.0.1/tests/test_perfect_domain_context_handler.py +148 -0
  64. hlit-0.0.1/tests/test_scatterplot_density.py +59 -0
  65. hlit-0.0.1/tests/test_settings_handler.py +27 -0
  66. hlit-0.0.1/tests/test_widgets_outputs.py +29 -0
  67. hlit-0.0.1/tests/test_workflows.py +80 -0
@@ -0,0 +1,20 @@
1
+ Metadata-Version: 2.1
2
+ Name: HLIT
3
+ Version: 0.0.1
4
+ Home-page:
5
+ Author: Random but skilled people
6
+ Author-email:
7
+ Keywords: orange3 add-on
8
+ License-File: License.txt
9
+ Requires-Dist: torch==2.2.2
10
+ Requires-Dist: sentence-transformers
11
+ Requires-Dist: gpt4all
12
+ Requires-Dist: sacremoses
13
+ Requires-Dist: transformers
14
+ Requires-Dist: sentencepiece
15
+ Requires-Dist: optuna
16
+ Requires-Dist: spacy==3.7.6
17
+ Requires-Dist: markdown
18
+ Requires-Dist: uvicorn
19
+ Requires-Dist: fastapi
20
+ Requires-Dist: python-multipart
@@ -0,0 +1,65 @@
1
+ License.txt
2
+ setup.py
3
+ HLIT.egg-info/PKG-INFO
4
+ HLIT.egg-info/SOURCES.txt
5
+ HLIT.egg-info/dependency_links.txt
6
+ HLIT.egg-info/entry_points.txt
7
+ HLIT.egg-info/namespace_packages.txt
8
+ HLIT.egg-info/requires.txt
9
+ HLIT.egg-info/top_level.txt
10
+ orangecontrib/OWInterface/__init__.py
11
+ orangecontrib/OWInterface/download/BaseLocalInterfaceWidget.py
12
+ orangecontrib/OWInterface/download/FileWatcher.py
13
+ orangecontrib/OWInterface/download/__init__.py
14
+ orangecontrib/OWInterface/webserver/__init__.py
15
+ orangecontrib/OWInterface/webserver/fileQueue.py
16
+ orangecontrib/OWInterface/webserver/main.py
17
+ orangecontrib/OWInterface/webserver/start_server.py
18
+ orangecontrib/OWInterface/webserver/utils.py
19
+ orangecontrib/OWInterface/widgets/OWDisplayOnInterface.py
20
+ orangecontrib/OWInterface/widgets/OWLocalInterface.py
21
+ orangecontrib/OWInterface/widgets/OWLocalInterfaceImages.py
22
+ orangecontrib/OWInterface/widgets/OWLocalInterfaceMultifile.py
23
+ orangecontrib/OWInterface/widgets/OWLocalInterfaceText.py
24
+ orangecontrib/OWInterface/widgets/__init__.py
25
+ orangecontrib/OWInterface/widgets/icons/MDViewer.png
26
+ orangecontrib/OWInterface/widgets/icons/Mistral.png
27
+ orangecontrib/OWInterface/widgets/icons/category.svg
28
+ orangecontrib/OWInterface/widgets/icons/dark_green.txt
29
+ orangecontrib/OWInterface/widgets/icons/documents.png
30
+ orangecontrib/OWInterface/widgets/icons/endloop.png
31
+ orangecontrib/OWInterface/widgets/icons/llm4all.svg
32
+ orangecontrib/OWInterface/widgets/icons/local_interf_img_multi_pull.svg
33
+ orangecontrib/OWInterface/widgets/icons/local_interf_multi_pull.svg
34
+ orangecontrib/OWInterface/widgets/icons/local_interf_pull.svg
35
+ orangecontrib/OWInterface/widgets/icons/local_interf_push.svg
36
+ orangecontrib/OWInterface/widgets/icons/local_interf_text_pull.svg
37
+ orangecontrib/OWInterface/widgets/icons/logo_solar.svg
38
+ orangecontrib/OWInterface/widgets/icons/logo_uncensoredsolar.svg
39
+ orangecontrib/OWInterface/widgets/icons/logo_upload.png
40
+ orangecontrib/OWInterface/widgets/icons/optimisation.png
41
+ orangecontrib/OWInterface/widgets/icons/owchunking.png
42
+ orangecontrib/OWInterface/widgets/icons/owedittable.svg
43
+ orangecontrib/OWInterface/widgets/icons/owembeddings.svg
44
+ orangecontrib/OWInterface/widgets/icons/owlemmatizer.svg
45
+ orangecontrib/OWInterface/widgets/icons/owmodel_helsinki_en_fr.svg
46
+ orangecontrib/OWInterface/widgets/icons/owmodel_helsinki_fr_en.svg
47
+ orangecontrib/OWInterface/widgets/icons/owmodel_mpnet.svg
48
+ orangecontrib/OWInterface/widgets/icons/owmodel_spacymd_fr.svg
49
+ orangecontrib/OWInterface/widgets/icons/owoptimisation.svg
50
+ orangecontrib/OWInterface/widgets/icons/owoptimisationselection.png
51
+ orangecontrib/OWInterface/widgets/icons/owqueryllm.svg
52
+ orangecontrib/OWInterface/widgets/icons/owtranslation.svg
53
+ orangecontrib/OWInterface/widgets/icons/qwen-color.png
54
+ orangecontrib/OWInterface/widgets/icons/startloop.png
55
+ orangecontrib/OWInterface/widgets/icons/widgetFactory.svg
56
+ tests/test_class_values_context_handler.py
57
+ tests/test_credentials.py
58
+ tests/test_domain_context_handler.py
59
+ tests/test_gui.py
60
+ tests/test_matplotlib_export.py
61
+ tests/test_perfect_domain_context_handler.py
62
+ tests/test_scatterplot_density.py
63
+ tests/test_settings_handler.py
64
+ tests/test_widgets_outputs.py
65
+ tests/test_workflows.py
@@ -0,0 +1,2 @@
1
+ [orange.widgets]
2
+ Advanced Artificial Intelligence Tools = orangecontrib.OWInterface.widgets
@@ -0,0 +1 @@
1
+ orangecontrib
@@ -0,0 +1,12 @@
1
+ torch==2.2.2
2
+ sentence-transformers
3
+ gpt4all
4
+ sacremoses
5
+ transformers
6
+ sentencepiece
7
+ optuna
8
+ spacy==3.7.6
9
+ markdown
10
+ uvicorn
11
+ fastapi
12
+ python-multipart
@@ -0,0 +1 @@
1
+ orangecontrib
hlit-0.0.1/License.txt ADDED
@@ -0,0 +1,6 @@
1
+ THIS SOFTWARE IS PROVIDED "AS IS", WITHOUT ANY WARRANTY WHATSOEVER.
2
+
3
+ If you use or redistribute this software, you are permitted to do so
4
+ under the terms of GNU [GPL-3.0]+ license.
5
+
6
+ [GPL-3.0]: https://www.gnu.org/licenses/gpl-3.0.en.html
hlit-0.0.1/PKG-INFO ADDED
@@ -0,0 +1,20 @@
1
+ Metadata-Version: 2.1
2
+ Name: HLIT
3
+ Version: 0.0.1
4
+ Home-page:
5
+ Author: Random but skilled people
6
+ Author-email:
7
+ Keywords: orange3 add-on
8
+ License-File: License.txt
9
+ Requires-Dist: torch==2.2.2
10
+ Requires-Dist: sentence-transformers
11
+ Requires-Dist: gpt4all
12
+ Requires-Dist: sacremoses
13
+ Requires-Dist: transformers
14
+ Requires-Dist: sentencepiece
15
+ Requires-Dist: optuna
16
+ Requires-Dist: spacy==3.7.6
17
+ Requires-Dist: markdown
18
+ Requires-Dist: uvicorn
19
+ Requires-Dist: fastapi
20
+ Requires-Dist: python-multipart
File without changes
@@ -0,0 +1,88 @@
1
+ from Orange.widgets import widget, gui, settings
2
+ from Orange.data import Table
3
+ from pathlib import Path
4
+ import json
5
+ from ..download.FileWatcher import FileWatcher
6
+ from ..webserver.start_server import start_server
7
+
8
+ class BaseLocalInterfaceWidget(widget.OWWidget, openclass=True):
9
+ # Common settings across all widgets
10
+ workflow_id = settings.Setting("default.ows") # type: ignore
11
+ input_id = settings.Setting("default_id") # type: ignore
12
+
13
+ class Outputs:
14
+ data = widget.Output("Data", Table)
15
+
16
+ def __init__(self):
17
+ super().__init__()
18
+ # GUI elements common to all widgets
19
+ self.info_label = gui.label(self.controlArea, self, "Initial info.")
20
+ self.workflow_id_edit = gui.lineEdit(self.controlArea, self, "workflow_id",
21
+ label="Workflow ID:", orientation="horizontal")
22
+ self.input_id_edit = gui.lineEdit(self.controlArea, self, "input_id",
23
+ label="input ID:", orientation="horizontal")
24
+
25
+ # Set up file watcher for all widgets
26
+ self.queue_file_path = self.setup_paths()
27
+ self.file_watcher = FileWatcher(str(self.queue_file_path))
28
+ self.file_watcher.file_modified.connect(self.process_queue)
29
+ # Start server for all widgets
30
+ start_server()
31
+
32
+ def setup_paths(self) -> Path:
33
+ # Set default path, can be overridden in derived class if needed
34
+ return Path(__file__).parent.parent / "webserver" / "received_files" / "in_process_queue.json"
35
+
36
+
37
+
38
+
39
+ def get_files_to_process(self, entry) -> list[Path]:
40
+ try:
41
+ self.opening_method
42
+ except AttributeError:
43
+ raise NotImplementedError("Derived classes must give a value for the attribute 'opening_method'.")
44
+
45
+ if entry.get("workflow_id") != self.workflow_id:
46
+ return []
47
+
48
+ file_to_process = []
49
+ for file_entry in entry.get("file_entries", []):
50
+ if file_entry.get("file_id") == self.input_id \
51
+ and file_entry.get("opening_method") == self.opening_method:
52
+ file_path = Path(file_entry["input_filename"])
53
+ if file_path.exists():
54
+ file_to_process.append(file_path)
55
+ else:
56
+ self.info_label.setText(f"File not found: {str(file_path)}")
57
+ print("file not found: ", str(file_path))
58
+
59
+ return file_to_process
60
+
61
+
62
+
63
+ def process_queue(self) -> None:
64
+ # Standard queue processing logic
65
+ if not self.queue_file_path.exists():
66
+ self.info_label.setText("Queue file not found.")
67
+ return
68
+
69
+ try:
70
+ with open(self.queue_file_path, 'r') as queue_file:
71
+ content = queue_file.read().strip()
72
+ if not content:
73
+ self.info_label.setText("Queue file is empty.")
74
+ return
75
+ files_to_process = json.loads(content)
76
+ except Exception as e:
77
+ self.info_label.setText(f"Error reading queue file: {e}")
78
+
79
+ entries_to_process = [entry for entry in files_to_process if entry.get("workflow_id") == self.workflow_id]
80
+ assert len(entries_to_process) <= 1, "Multiple entries found for a single workflow ID."
81
+ if entries_to_process:
82
+ files_to_process = self.get_files_to_process(entries_to_process[0])
83
+ self.process_files(files_to_process)
84
+
85
+
86
+ def process_files(self, files_to_process: list[Path]):
87
+ # To be implemented in derived classes
88
+ raise NotImplementedError("Derived classes from BaseDownloadWidget must implement the process_entry method.")
@@ -0,0 +1,17 @@
1
+ from pathlib import Path
2
+ from AnyQt.QtCore import QObject, pyqtSignal, QFileSystemWatcher
3
+
4
+ class FileWatcher(QObject):
5
+ file_modified = pyqtSignal(str)
6
+
7
+ def __init__(self, file_path: str):
8
+ super(FileWatcher, self).__init__()
9
+ self.watcher = QFileSystemWatcher()
10
+ if not Path(file_path).exists():
11
+ Path(file_path).parent.mkdir(parents=True, exist_ok=True)
12
+ Path(file_path).touch()
13
+ self.watcher.addPath(file_path)
14
+ self.watcher.fileChanged.connect(self.on_file_modified)
15
+
16
+ def on_file_modified(self, file_path):
17
+ self.file_modified.emit(file_path)
@@ -0,0 +1,37 @@
1
+ import json
2
+ from pathlib import Path
3
+ from typing import Any, Dict, List
4
+
5
+
6
+ class FileQueue:
7
+ def __init__(self, file_path: Path):
8
+ self.file_path: Path = file_path # path to json file to be processed
9
+ self.queue: List[Dict[str, Any]] = []
10
+ self.file_path.parent.mkdir(parents=True, exist_ok=True)
11
+ self.file_path.touch(exist_ok=True)
12
+
13
+ def load_queue(self) -> List[Dict[str, Any]]:
14
+ """Load queue from the file, or initialize an empty queue if the file does not exist."""
15
+ if self.file_path.exists():
16
+ with open(self.file_path, 'r') as file:
17
+ return json.load(file)
18
+ else:
19
+ return []
20
+
21
+ def save_queue(self) -> None:
22
+ """Persist the current state of the queue to a file."""
23
+ with open(self.file_path, 'w') as file:
24
+ json.dump(self.queue, file)
25
+
26
+ def add(self, item: Dict[str, Any]) -> None:
27
+ """Add an item to the queue and save the updated queue."""
28
+ self.queue.append(item)
29
+ self.save_queue()
30
+
31
+ def remove(self, item: Dict[str, Any]) -> None:
32
+ """Remove an item from the queue and save the updated queue."""
33
+ if item in self.queue:
34
+ self.queue.remove(item)
35
+ self.save_queue()
36
+ else:
37
+ print(f"Attempted to remove non-existent item from queue: {item}")
@@ -0,0 +1,270 @@
1
+ import asyncio
2
+ import os
3
+ import time
4
+ from contextlib import asynccontextmanager
5
+ from pathlib import Path
6
+ from typing import Any, Dict, List
7
+
8
+ from fastapi import FastAPI, File, HTTPException, UploadFile
9
+ from fastapi.middleware.cors import CORSMiddleware
10
+ from fastapi.responses import FileResponse, JSONResponse
11
+
12
+ from fileQueue import FileQueue
13
+ from utils import (generate_unique_output_folder, hash_file_content, make_list,
14
+ zip_folder)
15
+
16
+
17
+ @asynccontextmanager
18
+ async def lifespan(app: FastAPI):
19
+ os.makedirs(save_directory, exist_ok=True)
20
+ os.makedirs(output_directory, exist_ok=True)
21
+ asyncio.create_task(process_files_queue())
22
+ yield
23
+
24
+ app = FastAPI(lifespan=lifespan)
25
+ # CORS Settings
26
+ app.add_middleware(
27
+ CORSMiddleware,
28
+ allow_origins=["*"], # List of origins that are allowed, '*' means allow all origins
29
+ allow_credentials=True,
30
+ allow_methods=["*"], # List of HTTP methods that are allowed, '*' means allow all methods
31
+ allow_headers=["*"], # List of headers that are allowed, '*' means allow all headers
32
+ )
33
+
34
+ # Constants
35
+ MAX_PROCESSING_QUEUE_LENGTH: int = 1
36
+ TIMEOUT_LIMIT: int = 120 # seconds
37
+
38
+ # Path settingsmatch_number
39
+ save_directory: Path = Path(__file__).parent / "received_files"
40
+ output_directory: Path = Path(__file__).parent / "sent_files"
41
+
42
+ print("save_directory: ", save_directory)
43
+ print("output_directory: ", output_directory)
44
+
45
+ waiting_queue: FileQueue = FileQueue(save_directory / "waiting_queue.json")
46
+ in_process_queue: FileQueue = FileQueue(save_directory / "in_process_queue.json")
47
+
48
+ def make_tuple_list(text_inputs: List[str]) -> List[tuple[str, str]]:
49
+ assert len(text_inputs) % 2 == 0, "The number of text inputs must be even."
50
+ print("text_inputs: ", text_inputs)
51
+ print("return: ", [(text_inputs[i], text_inputs[i+1]) for i in range(0, len(text_inputs), 2)])
52
+ return [(text_inputs[i], text_inputs[i+1]) for i in range(0, len(text_inputs), 2)]
53
+
54
+ # Main API Endpoints
55
+ @app.post("/upload-files/")
56
+ async def upload_files(
57
+ file_ids: List[str],
58
+ workflow_id: str,
59
+ opening_methods: List[str],
60
+ expected_nb_outputs: int,
61
+ files: List[UploadFile] = File(...),
62
+ text_inputs: List[str] = []
63
+ ) -> JSONResponse:
64
+ """
65
+ Upload multiple files to the server for processing through a Orange workflow.
66
+
67
+ Args:
68
+ - file_ids (List[str]): List of unique file IDs corresponding to the files.
69
+ The IDs should match the ones configured in the Orange workflow.
70
+ - workflow_id (str): Unique ID of the workflow.
71
+ The ID should match the one configured in the Orange workflow.
72
+ - opening_methods (List[str]): List of opening methods for the files.
73
+ Choose from 'image_file', 'multiple_file', or 'file'.
74
+ - expected_nb_outputs (int): Expected number of output files (depending on your workflow).
75
+ - files (List[UploadFile]): List of files to be uploaded.
76
+ - text_inputs (List[str]): List of text inputs for the workflow. Must be in the format [input_id1, value1, input_id2, value2].
77
+
78
+ Returns:
79
+ JSONResponse: Response message with the unique ID of the processing task."""
80
+ text_inputs = make_list(text_inputs)
81
+ opening_methods = make_list(opening_methods)
82
+ print(file_ids, opening_methods)
83
+ if len(files) != len(file_ids) or len(files) != len(opening_methods):
84
+ raise HTTPException(status_code=400, detail="Number of files, file IDs, and opening methods must match.")
85
+
86
+ file_entries: List[Dict[str, Any]] = []
87
+ for file, file_id, opening_method in zip(files, file_ids, opening_methods):
88
+ if opening_method not in ["image_file", "multiple_file", "file"]:
89
+ raise HTTPException(status_code=400, detail="Invalid opening method provided. Choose from 'image_file', 'multiple_file', or 'file'.")
90
+
91
+ content: bytes = await file.read()
92
+ file_hash: str = hash_file_content(content)
93
+ input_filename: str = str(save_directory / str(file.filename))
94
+
95
+ # Save the file locally
96
+ with open(input_filename, 'wb') as f:
97
+ f.write(content)
98
+
99
+ file_entries.append({
100
+ 'input_filename': input_filename,
101
+ 'file_id': file_id,
102
+ 'file_hash': file_hash,
103
+ 'opening_method': opening_method,
104
+ })
105
+
106
+ unique_id, output_folder = generate_unique_output_folder(output_directory)
107
+
108
+ waiting_queue.add({
109
+ 'unique_id': unique_id,
110
+ 'workflow_id': workflow_id,
111
+ 'file_entries': file_entries,
112
+ 'output_folder': str(output_folder),
113
+ 'expected_nb_outputs': expected_nb_outputs,
114
+ 'text_inputs': text_inputs
115
+ })
116
+
117
+ return JSONResponse(content={"message": "Files queued for processing", "unique_id": unique_id})
118
+
119
+ @app.post("/upload-files-via-path/")
120
+ async def upload_files_via_path(
121
+ filepaths: List[str],
122
+ file_ids: List[str],
123
+ opening_methods: List[str],
124
+ workflow_id: str,
125
+ expected_nb_outputs: int,
126
+ text_inputs: List[tuple[str, str]] = []
127
+ ) -> JSONResponse:
128
+ """
129
+ Upload multiple files to the server for processing through a Orange workflow.
130
+
131
+ Args:
132
+ - filepaths (List[str]): List of file paths to be uploaded.
133
+ - file_ids (List[str]): List of unique file IDs corresponding to the files.
134
+ The IDs should match the ones configured in the Orange workflow.
135
+ - opening_methods (List[str]): List of opening methods for the files.
136
+ Choose from 'image_file', 'multiple_file', or 'file'.
137
+ - workflow_id (str): Unique ID of the workflow.
138
+ The ID should match the one configured in the Orange workflow.
139
+ - expected_nb_outputs (int): Expected number of output files (depending on your workflow).
140
+
141
+ Returns:
142
+ JSONResponse: Response message with the unique ID of the processing task."""
143
+ file_ids = make_list(file_ids)
144
+ opening_methods = make_list(opening_methods)
145
+ filepaths = make_list(filepaths)
146
+ if len(filepaths) != len(file_ids) or len(file_ids) != len(opening_methods):
147
+ raise HTTPException(status_code=400, detail="Number of file paths, file IDs, and opening methods must match.")
148
+
149
+ file_entries: List[Dict[str, Any]] = []
150
+ for filepath, file_id, opening_method in zip(filepaths, file_ids, opening_methods):
151
+ if opening_method not in ["image_file", "multiple_file", "file"]:
152
+ raise HTTPException(status_code=400, detail="Invalid opening method provided.")
153
+
154
+ file_path: Path = Path(filepath)
155
+ if not file_path.exists():
156
+ raise HTTPException(status_code=404, detail=f"File not found: {filepath}")
157
+
158
+ with file_path.open('rb') as f:
159
+ content: bytes = f.read()
160
+
161
+ file_hash: str = hash_file_content(content)
162
+ file_entries.append({
163
+ 'input_filename': str(file_path),
164
+ 'file_id': file_id,
165
+ 'file_hash': file_hash,
166
+ 'opening_method': opening_method
167
+ })
168
+
169
+ unique_id, output_folder = generate_unique_output_folder(output_directory)
170
+
171
+ waiting_queue.add({
172
+ 'unique_id': unique_id,
173
+ 'workflow_id': workflow_id,
174
+ 'file_entries': file_entries,
175
+ 'output_folder': str(output_folder),
176
+ 'expected_nb_outputs': expected_nb_outputs,
177
+ 'text_inputs': text_inputs
178
+ })
179
+
180
+ return JSONResponse(content={"message": "Files queued for processing", "unique_id": unique_id})
181
+
182
+ @app.get("/retrieve-outputs/{unique_id}", response_model=None)
183
+ async def retrieve_outputs(unique_id: str, file_id: str = "") -> FileResponse | JSONResponse:
184
+ """
185
+ Retrieve the output files for a given unique ID. By default, a zip of all files will be returned.
186
+ If a specific output filename is provided, only that file will be returned.
187
+ **IMPORTANT** : If the processing is not complete, the method will return a 404 error. You have to keep calling this method until the processing is complete.
188
+
189
+ Args:
190
+ - unique_id (str): Unique ID of the processing task.
191
+ - file_id (str): Optional file ID to retrieve a specific file. If not provided, a zip of all files will be returned.
192
+
193
+ Returns:
194
+ FileResponse | JSONResponse: Response with the output file(s) for download.
195
+ """
196
+ output_folder = output_directory / unique_id
197
+
198
+ # Check if the processing is complete by checking the presence of the "done" file
199
+ if (output_folder / "done").exists():
200
+ all_files = list(output_folder.glob('*'))
201
+
202
+ # Remove 'done' and 'output.zip' files from the list
203
+ for file in [output_folder / "done", output_folder / "output.zip"]:
204
+ if file.exists():
205
+ all_files.remove(file)
206
+
207
+ # If a specific file_id is provided, search for it in the output folder
208
+ if file_id:
209
+ for file in all_files:
210
+ if file_id in file.name:
211
+ return FileResponse(str(file), media_type='application/octet-stream', filename=file.name)
212
+ return JSONResponse(content={"message": f"File with ID {file_id} not found."}, status_code=404)
213
+
214
+ # If no specific file_id is specified, handle the retrieval of multiple or single files
215
+ if len(all_files) == 1:
216
+ # Return the single file if only one file is present
217
+ output_file = all_files[0]
218
+ return FileResponse(str(output_file), media_type='application/octet-stream', filename=output_file.name)
219
+ elif len(all_files) > 1:
220
+ # Create a zip of all the output files for download
221
+ output_zip: Path = output_folder / "output.zip"
222
+ zip_folder(output_folder, output_zip)
223
+ return FileResponse(str(output_zip), media_type='application/zip', filename=f"output.zip")
224
+ else:
225
+ return JSONResponse(content={"message": "No files found in the output folder."}, status_code=404)
226
+
227
+ elif output_folder.exists():
228
+ return JSONResponse(content={"message": "Processing is not complete."}, status_code=404)
229
+ else:
230
+ return JSONResponse(content={"message": "Unique ID not found."}, status_code=404)
231
+
232
+ @app.get("/ping")
233
+ async def ping() -> JSONResponse:
234
+ return JSONResponse(content={"message": "pong"})
235
+
236
+
237
+
238
+ # Background Processing Task
239
+ async def process_files_queue() -> None:
240
+ """
241
+ Background task to process files from the waiting queue.
242
+ This task will check the waiting queue for new files and move them to the in-process queue.
243
+ It will then wait for the expected number of output files to be generated by the workflow.
244
+ """
245
+
246
+ while True:
247
+ if not waiting_queue.queue or len(in_process_queue.queue) >= MAX_PROCESSING_QUEUE_LENGTH:
248
+ await asyncio.sleep(1)
249
+ continue
250
+
251
+ workflow_entry= waiting_queue.queue[0] # element en attente
252
+ waiting_queue.remove(workflow_entry)
253
+ in_process_queue.add(workflow_entry) # element en process
254
+ expected_nb_outputs: int = workflow_entry['expected_nb_outputs']
255
+ output_folder: Path = Path(workflow_entry['output_folder'])
256
+
257
+ # Wait for the expected number of output files to be generated by the workflow
258
+ start_time: float = time.time()
259
+ output_folder: Path = Path(workflow_entry['output_folder'])
260
+ while time.time() - start_time < TIMEOUT_LIMIT:
261
+ if len(list(output_folder.glob('*'))) == expected_nb_outputs:
262
+ break
263
+ elif len(list(output_folder.glob('*'))) > expected_nb_outputs:
264
+ raise Exception("Too many files found in the output folder. Error.")
265
+ await asyncio.sleep(1)
266
+
267
+ in_process_queue.remove(workflow_entry)
268
+ (output_folder / "done").touch()
269
+
270
+
@@ -0,0 +1,70 @@
1
+ import os
2
+ import socket
3
+ import subprocess
4
+ import sys
5
+ import threading
6
+ from logging import getLogger
7
+ from pathlib import Path
8
+ from typing import Literal
9
+
10
+ from uvicorn import Config, Server
11
+
12
+ logger = getLogger(__name__)
13
+
14
+ def is_port_in_use(port: int) -> bool:
15
+ """Check if a port is already in use."""
16
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
17
+ return s.connect_ex(('127.0.0.1', port)) == 0
18
+
19
+
20
+ def start_server(port: int = 8000, method: Literal["new_terminal", "same_terminal"] = "new_terminal") -> None:
21
+ print("Start server called with method: ", method)
22
+ if is_port_in_use(port):
23
+ print("Server is already running.")
24
+ return
25
+ if method == "new_terminal":
26
+ _start_server_in_new_terminal(port)
27
+ elif method == "same_terminal":
28
+ _start_server_in_same_terminal(port)
29
+ else:
30
+ print(f"Invalid method: {method}")
31
+
32
+
33
+ def _start_server_in_new_terminal(port: int = 8000):
34
+ """Starts the server in a new terminal."""
35
+ path_uvicorn="uvicorn"
36
+ if os.name == "nt":
37
+ path_uvicorn=os.path.dirname(sys.executable)
38
+ path_uvicorn=path_uvicorn.replace("\\","/")
39
+ path_uvicorn+="/Scripts/uvicorn.exe"
40
+ if not os.path.isfile(path_uvicorn):
41
+ path_uvicorn="uvicorn"
42
+ command = f"{path_uvicorn} main:app --port {port}"
43
+ path = Path(__file__).parent
44
+ server_process = subprocess.Popen(['cmd.exe', '/c', f'start', 'cmd', '/k', command], cwd=path)
45
+
46
+ if __name__ == "__main__":
47
+ start_server()
48
+
49
+
50
+ def _start_server_in_same_terminal(port: int = 8000) -> None:
51
+ """Starts the server in a separate thread."""
52
+ def run_server():
53
+ """Internal function to configure and run the Uvicorn server."""
54
+
55
+ upper_folder = Path(__file__).parent
56
+ sys.path.append(str(upper_folder))
57
+ config = Config(app="main:app", port=port)
58
+ server = Server(config)
59
+
60
+ try:
61
+ server.run()
62
+ except Exception as e:
63
+ print(f"Error: {e}")
64
+
65
+ # Start the server in a new daemon thread
66
+ server_thread = threading.Thread(target=run_server, daemon=True)
67
+ server_thread.daemon = True
68
+ server_thread.start()
69
+
70
+ print("Server started on a separate thread.")
@@ -0,0 +1,38 @@
1
+
2
+
3
+ import hashlib
4
+ import uuid
5
+ import zipfile
6
+ from pathlib import Path
7
+ from typing import Tuple
8
+
9
+
10
+ def hash_file_content(content: bytes) -> str:
11
+ """Compute the MD5 hash of a given content."""
12
+ return hashlib.md5(content).hexdigest()
13
+
14
+ def generate_unique_output_folder(output_directory: Path) -> Tuple[str, Path]:
15
+ """Generate a directory for the outputs using a UUID."""
16
+ unique_id: str = str(uuid.uuid4())
17
+ output_folder: Path = output_directory / unique_id
18
+ output_folder.mkdir(exist_ok=True)
19
+ return unique_id, output_folder
20
+
21
+ def make_list(liste: list) -> list:
22
+ """Convert a string with comma-separated values to a list."""
23
+ if len(liste) == 1 and "," in liste[0]:
24
+ return liste[0].split(",")
25
+ else:
26
+ return liste
27
+
28
+ def zip_folder(source_dir: Path, output_filename: Path, excluded_files: list[str]=["done", "output.zip"]):
29
+ """Zip the contents of a folder, excluding certain files."""
30
+ if output_filename.exists():
31
+ print("Output file already exists. Skipping zipping.")
32
+ return
33
+ with zipfile.ZipFile(output_filename, 'w', zipfile.ZIP_DEFLATED) as zipf:
34
+ for file_path in source_dir.rglob('*'):
35
+ if file_path.is_file() and file_path.name not in excluded_files:
36
+ # Write the file to the archive with an appropriate relative path
37
+ zipf.write(file_path, file_path.relative_to(source_dir))
38
+