Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/main/python/systemds/scuro/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
("dataloader.video_loader", "VideoLoader"),
("dataloader.text_loader", "TextLoader"),
("dataloader.json_loader", "JSONLoader"),
("dataloader.ocr_loader", "OCRLoader"),
("dataloader.tabular_loader", "TabularLoader"),
(
"representations.representation",
Expand Down Expand Up @@ -81,6 +82,7 @@
("modality.transformed", "TransformedModality"),
("modality.type", "ModalityType"),
("modality.unimodal_modality", "UnimodalModality"),
("modality.paired_modality", "PairedModality PairedOperation"),
("drsearch.task", "Task"),
("drsearch.evaluation_split", "EvaluationSplit"),
("drsearch.operator_registry", "Registry"),
Expand Down Expand Up @@ -132,6 +134,7 @@ def __getattr__(name):
"AudioLoader",
"VideoLoader",
"TextLoader",
"OCRLoader",
"Representation",
"Aggregation",
"AggregatedRepresentation",
Expand Down Expand Up @@ -179,6 +182,8 @@ def __getattr__(name):
"TransformedModality",
"ModalityType",
"UnimodalModality",
"PairedModality",
"PairedOperation",
"Task",
"Registry",
"OptimizationData",
Expand Down
2 changes: 1 addition & 1 deletion src/main/python/systemds/scuro/dataloader/audio_loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ def _decode_file(self, file: str):
if self.normalize:
audio = librosa.util.normalize(audio)

return audio, self.modality_type.create_metadata(sr, audio)
return audio, {**self.modality_type.create_metadata(sr, audio), "file": file}

def extract(self, file: str, index: Optional[Union[str, List[str]]] = None):
audio, metadata = self._decode_file(file)
Expand Down
15 changes: 10 additions & 5 deletions src/main/python/systemds/scuro/dataloader/image_loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,12 @@ def load(self):
if self.chunk_size:
return super().load()

self.data = LazyFileSequence(
self.get_file_names(self.indices), self._decode_file
)
self.metadata = self._all_metadata.copy()
file_names = self.get_file_names(self.indices)
self.data = LazyFileSequence(file_names, self._decode_file)
self.metadata = [
{**metadata, "file": file}
for metadata, file in zip(self._all_metadata, file_names)
]
return self.data, self.metadata

def _decode_file(self, file: str):
Expand All @@ -90,7 +92,10 @@ def extract(self, file: str, index: Optional[Union[str, List[str]]] = None):
height, width, channels = image.shape

self.metadata.append(
self.modality_type.create_metadata(width, height, channels)
{
**self.modality_type.create_metadata(width, height, channels),
"file": file,
}
)

self.data.append(image)
Expand Down
9 changes: 8 additions & 1 deletion src/main/python/systemds/scuro/dataloader/json_loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,15 @@ def extract(self, file: str, index: Optional[Union[str, List[str]]] = None):
text = self._get_text(record)

self.data.append(text)
file_reference = {"file": file}
if record is not json_file:
file_reference["file_idx"] = idx
self.metadata.append(
{**self.modality_type.create_metadata(len(text), text), **record}
{
**self.modality_type.create_metadata(len(text), text),
**record,
**file_reference,
}
)

def get_stats(self, source_path: str):
Expand Down
97 changes: 97 additions & 0 deletions src/main/python/systemds/scuro/dataloader/ocr_loader.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
# -------------------------------------------------------------
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
# -------------------------------------------------------------
from typing import List, Optional, Union

import numpy as np

from systemds.scuro.dataloader.base_loader import BaseLoader
import cv2
import pytesseract
from systemds.scuro.modality.type import ModalityType


class OCRLoader(BaseLoader):
"""
Loads images and extracts their textual content using the Tesseract OCR
engine. The recognized text is exposed as a TEXT modality so that it can be
further processed by the text representations.

Requires the Tesseract binary to be installed on the system as well as the
``pytesseract`` python wrapper.
"""

def __init__(
self,
source_path: str,
indices: List[str],
data_type: Union[np.dtype, str] = str,
chunk_size: Optional[int] = None,
load=True,
ext=".jpg",
language: str = "eng",
config: str = "",
):
"""
:param source_path: The location where the raw images lie
:param indices: A list of indices as strings corresponding to the file names
:param data_type: The data type the recognized text is stored as
:param chunk_size: An optional argument to load the data in chunks
:param load: Whether the data is read from file
:param ext: The file extension of the images
:param language: The language(s) passed to Tesseract (e.g. ``"eng"`` or ``"eng+deu"``)
:param config: Additional configuration flags forwarded to Tesseract
"""
super().__init__(
source_path, indices, data_type, chunk_size, ModalityType.TEXT, ext
)
self.load_data_from_file = load
self.language = language
self.config = config

def extract(self, file: str, index: Optional[Union[str, List[str]]] = None):
self.file_sanity_check(file)

image = cv2.imread(file, cv2.IMREAD_COLOR)
# cv2.imread signals an undecodable file by *returning None* rather
# than raising. Passing that straight into cvtColor reaches OpenCV's
# native assertion layer, which depending on the build aborts the
# interpreter outright instead of raising -- killing the process with
# no Python traceback. Fail loudly here so the caller can log it.
if image is None:
raise ValueError(
f"cv2 could not decode image {file} (unsupported format, or "
f"truncated/corrupt file)"
)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

text = pytesseract.image_to_string(
image, lang=self.language, config=self.config
)
text = text.replace("\n", " ").strip()

self.metadata.append(
{
**self.modality_type.create_metadata(len(text.split()), text),
"file": file,
}
)

self.data.append(text)
5 changes: 4 additions & 1 deletion src/main/python/systemds/scuro/dataloader/pdf_loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,10 @@ def extract(self, file: str, index: Optional[Union[str, List[str]]] = None):
image = image.astype(np.uint8, copy=False)

self.metadata.append(
self.modality_type.create_metadata(width, height, channels)
{
**self.modality_type.create_metadata(width, height, channels),
"file": file,
}
)

self.data.append(image)
5 changes: 4 additions & 1 deletion src/main/python/systemds/scuro/dataloader/text_loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,10 @@ def extract(self, file: str, index: Optional[Union[str, List[str]]] = None):
line = re.sub(self.prefix, "", line)
line = line.replace("\n", "")
self.metadata.append(
self.modality_type.create_metadata(len(line.split()), line)
{
**self.modality_type.create_metadata(len(line.split()), line),
"file": file,
}
)
self.data.append(line)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,9 +99,12 @@ def extract(self, file: str, index: Optional[Union[str, List[str]]] = None):
else:
for i, index in enumerate(self.indices):
self.metadata.append(
self.modality_type.create_metadata(
self.signal_names, data[i], self.sampling_rate
)
{
**self.modality_type.create_metadata(
self.signal_names, data[i], self.sampling_rate
),
"file": file,
}
)
self.data.append(data[i])

Expand Down
61 changes: 56 additions & 5 deletions src/main/python/systemds/scuro/dataloader/transcript_loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,14 @@
# under the License.
#
# -------------------------------------------------------------
from typing import List, Optional, Union
import warnings
from typing import List, Optional, Tuple, Union
from faster_whisper import WhisperModel
import numpy as np

from systemds.scuro.dataloader.base_loader import BaseLoader
from systemds.scuro.modality.type import ModalityType
from systemds.scuro.utils.static_variables import get_device


class TranscriptLoader(BaseLoader):
Expand All @@ -35,15 +37,64 @@ def __init__(
chunk_size: Optional[int] = None,
normalize: bool = True,
transcribe_model_size: str = "medium",
device: Optional[str] = None,
gpu_id: Optional[int] = None,
load=True,
):
super().__init__(source_path, indices, data_type, chunk_size, ModalityType.TEXT)
self.model = WhisperModel(
transcribe_model_size, device="cpu", compute_type="int8"
)
self.model = self._load_model(transcribe_model_size, device, gpu_id)
self.normalize = normalize
self.load_data_from_file = load

@staticmethod
def _resolve_device(
device: Optional[str], gpu_id: Optional[int]
) -> Tuple[str, int, str]:
"""
faster-whisper runs on CTranslate2, not torch, so it wants a device
string plus an index instead of a torch.device. Map get_device() onto
that triple and pick the compute type that fits the device: float16 on
GPU, int8 on CPU.
"""
if device is None:
torch_device = get_device(gpu_id)
device = torch_device.type
device_index = torch_device.index if torch_device.index is not None else 0
else:
device_index = gpu_id if gpu_id is not None else 0

compute_type = "float16" if device == "cuda" else "int8"
return device, device_index, compute_type

def _load_model(
self,
transcribe_model_size: str,
device: Optional[str],
gpu_id: Optional[int],
) -> WhisperModel:
device, device_index, compute_type = self._resolve_device(device, gpu_id)

try:
return WhisperModel(
transcribe_model_size,
device=device,
device_index=device_index,
compute_type=compute_type,
)
except Exception as e: # noqa: BLE001
if device == "cpu":
raise
# A visible torch CUDA device does not guarantee CTranslate2 can use
# it: it loads its own cuBLAS/cuDNN and fails here when those are
# missing. Fall back rather than taking the whole run down.
warnings.warn(
f"Falling back to CPU transcription: could not load Whisper on "
f"{device}:{device_index} ({e})"
)
return WhisperModel(
transcribe_model_size, device="cpu", compute_type="int8"
)

def extract(self, file: str, index: Optional[Union[str, List[str]]] = None):
self.file_sanity_check(file)
segments, _ = self.model.transcribe(file, vad_filter=True)
Expand All @@ -54,6 +105,6 @@ def extract(self, file: str, index: Optional[Union[str, List[str]]] = None):
md["timestamp_end"] = seg.end
md["text"] = seg.text

self.metadata.append(md)
self.metadata.append({**md, "file": file})

self.data.append(seg.text)
15 changes: 9 additions & 6 deletions src/main/python/systemds/scuro/dataloader/video_loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,9 +74,10 @@ def __init__(
load=True,
fps=None,
target_size: Optional[Tuple[int, int]] = None,
ext=".mp4",
):
super().__init__(
source_path, indices, data_type, chunk_size, ModalityType.VIDEO
source_path, indices, data_type, chunk_size, ModalityType.VIDEO, ext
)
self.load_data_from_file = load
self.fps = fps
Expand All @@ -99,10 +100,12 @@ def load(self):
if self.chunk_size:
return super().load()

self.data = LazyFileSequence(
self.get_file_names(self.indices), self._decode_data
)
self.metadata = self._all_metadata.copy()
file_names = self.get_file_names(self.indices)
self.data = LazyFileSequence(file_names, self._decode_data)
self.metadata = [
{**metadata, "file": file}
for metadata, file in zip(self._all_metadata, file_names)
]
return self.data, self.metadata

def _decode_data(self, file: str):
Expand Down Expand Up @@ -191,7 +194,7 @@ def _decode_file(self, file: str):

def extract(self, file: str, index: Optional[Union[str, List[str]]] = None):
data, metadata = self._decode_file(file)
self.metadata.append(metadata)
self.metadata.append({**metadata, "file": file})
self.data.append(data)

def get_stats(self, source_path: str):
Expand Down
Loading