Skip to content
23 changes: 15 additions & 8 deletions aperturedb/BBoxDataCSV.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,14 +60,21 @@ class BBoxDataCSV(CSVParser.CSVParser):
def __init__(self, filename, df=None, use_dask=False):

super().__init__(filename, df=df, use_dask=use_dask)
if not use_dask:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This check ensures that a CSV file is not read at the first pass when dask mode is used. It's a performance optimization, but it's impact can be observed when using a file with millions of rows. I can explain more offline.

@JoshStoddard JoshStoddard May 2, 2023 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, sorry, forgot to hit send 🤦

My interpretation was that this was only making use of the header, which should already be populated by super().__init__() and validation().

In any event, for this PT, I only need the header row. Is there a way to get that without having to read the whole file?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see. I think we can merge it and worry about the optimization part later.

self.props_keys = [x for x in self.header[5:]
if not x.startswith(CSVParser.CONSTRAINTS_PREFIX)]
self.constraints_keys = [x for x in self.header[5:]
if x.startswith(CSVParser.CONSTRAINTS_PREFIX)]

self.img_key = self.header[0]
self.command = "AddBoundingBox"
self.props_keys = [x for x in self.header[5:]
if not x.startswith(CSVParser.CONSTRAINTS_PREFIX)]
self.constraints_keys = [x for x in self.header[5:]
if x.startswith(CSVParser.CONSTRAINTS_PREFIX)]

self.img_key = self.header[0]
self.command = "AddBoundingBox"

def get_indices(self):
return {
"entity": {
"_BoundingBox": self.get_indexed_properties()
}
}

def getitem(self, idx):
idx = self.df.index.start + idx
Expand Down Expand Up @@ -103,7 +110,7 @@ def getitem(self, idx):
}
abb = self._basic_command(idx, custom_fields)

properties = self.parse_properties(self.df, idx)
properties = self.parse_properties(idx)
if properties:
props = properties
if "_label" in props:
Expand Down
19 changes: 13 additions & 6 deletions aperturedb/BlobDataCSV.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,12 +50,19 @@ class BlobDataCSV(CSVParser.CSVParser):
def __init__(self, filename, df=None, use_dask=False):

super().__init__(filename, df=df, use_dask=use_dask)
if not use_dask:
self.props_keys = [x for x in self.header[1:]
if not x.startswith(CSVParser.CONSTRAINTS_PREFIX) and x != BLOB_PATH]
self.constraints_keys = [x for x in self.header[1:]
if x.startswith(CSVParser.CONSTRAINTS_PREFIX)]
self.command = "AddBlob"

self.props_keys = [x for x in self.header[1:]
if not x.startswith(CSVParser.CONSTRAINTS_PREFIX) and x != BLOB_PATH]
self.constraints_keys = [x for x in self.header[1:]
if x.startswith(CSVParser.CONSTRAINTS_PREFIX)]
self.command = "AddBlob"

def get_indices(self):
return {
"entity": {
"_Blob": self.get_indexed_properties()
}
}

def getitem(self, idx):
idx = self.df.index.start + idx
Expand Down
49 changes: 28 additions & 21 deletions aperturedb/CSVParser.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

ENTITY_CLASS = "EntityClass"
CONSTRAINTS_PREFIX = "constraint_"
DATE_PREFIX = "date:"
PROPERTIES = "properties"
CONSTRAINTS = "constraints"

Expand Down Expand Up @@ -60,42 +61,48 @@ def __init__(self, filename, df=None, use_dask=False):
def __len__(self):
return len(self.df.index)

def parse_properties(self, df, idx):
def get_indexed_properties(self):
if self.constraints_keys:
return {self._parse_prop(k)[0] for k in self.constraints_keys}
return set()

def get_indices(self):
raise NotImplementedError

def _parse_prop(self, key, val=None):
if key.startswith(CONSTRAINTS_PREFIX):
key = key[len(CONSTRAINTS_PREFIX):]
if key.startswith(DATE_PREFIX):
key = key[len(DATE_PREFIX):]
val = {"_date": val}
return key, val

def parse_properties(self, idx):

properties = {}
if len(self.props_keys) > 0:
if self.props_keys:
for key in self.props_keys:
# Handle Date data type
if key.startswith("date:"):
prop = key[len("date:"):] # remove prefix
properties[prop] = {"_date": self.df.loc[idx, key]}
else:
value = self.df.loc[idx, key]
if value == value: # skips nan values
properties[key] = value
prop, value = self._parse_prop(key, self.df.loc[idx, key])
if value == value: # skips nan values
properties[prop] = value

return properties

def parse_constraints(self, df, idx):
def parse_constraints(self, idx):

constraints = {}
if len(self.constraints_keys) > 0:
if self.constraints_keys:
for key in self.constraints_keys:
if key.startswith("constraint_date:"):
prop = key[len("constraint_date:"):] # remove prefix
constraints[prop] = [
"==", {"_date": self.df.loc[idx, key]}]
else:
prop = key[len(CONSTRAINTS_PREFIX):] # remove "prefix
constraints[prop] = ["==", self.df.loc[idx, key]]
prop, value = self._parse_prop(key, self.df.loc[idx, key])
constraints[prop] = ["==", value]

return constraints

def _basic_command(self, idx, custom_fields: dict = None):
if custom_fields == None:
custom_fields = {}
properties = self.parse_properties(self.df, idx)
constraints = self.parse_constraints(self.df, idx)
properties = self.parse_properties(idx)
constraints = self.parse_constraints(idx)
query = {
self.command: custom_fields
}
Expand Down
33 changes: 20 additions & 13 deletions aperturedb/ConnectionDataCSV.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,19 +56,26 @@ class ConnectionDataCSV(CSVParser):

def __init__(self, filename, df=None, use_dask=False):
super().__init__(filename, df=df, use_dask=use_dask)
if not use_dask:
self.props_keys = [x for x in self.header[3:]
if not x.startswith(CONSTRAINTS_PREFIX)]

self.constraints_keys = [x for x in self.header[3:]
if x.startswith(CONSTRAINTS_PREFIX)]

self.src_class = self.header[1].split("@")[0]
self.src_key = self.header[1].split("@")[1]
self.dst_class = self.header[2].split("@")[0]
# Pandas appends a .n to the column name if there is a duplicate
self.dst_key = self.header[2].split("@")[1].split(".")[0]
self.command = "AddConnection"

self.props_keys = [x for x in self.header[3:]
if not x.startswith(CONSTRAINTS_PREFIX)]

self.constraints_keys = [x for x in self.header[3:]
if x.startswith(CONSTRAINTS_PREFIX)]

self.src_class = self.header[1].split("@")[0]
self.src_key = self.header[1].split("@")[1]
self.dst_class = self.header[2].split("@")[0]
# Pandas appends a .n to the column name if there is a duplicate
self.dst_key = self.header[2].split("@")[1].split(".")[0]
self.command = "AddConnection"

def get_indices(self):
return {
"connection": {
cls: self.get_indexed_properties() for cls in self.df[CONNECTION_CLASS].unique()
}
}

def getitem(self, idx):
idx = self.df.index.start + idx
Expand Down
19 changes: 13 additions & 6 deletions aperturedb/DescriptorDataCSV.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,12 +73,19 @@ def __init__(self, filename, df=None, use_dask=False):
super().__init__(filename, df=df, use_dask=use_dask)
self.npy_arrays = {}
self.has_label = False
if not use_dask:
self.props_keys = [x for x in self.header[3:]
if not x.startswith(CSVParser.CONSTRAINTS_PREFIX)]
self.constraints_keys = [x for x in self.header[3:]
if x.startswith(CSVParser.CONSTRAINTS_PREFIX)]
self.command = "AddDescriptor"

self.props_keys = [x for x in self.header[3:]
if not x.startswith(CSVParser.CONSTRAINTS_PREFIX)]
self.constraints_keys = [x for x in self.header[3:]
if x.startswith(CSVParser.CONSTRAINTS_PREFIX)]
self.command = "AddDescriptor"

def get_indices(self):
return {
"entity": {
"_Descriptor": self.get_indexed_properties()
}
}

def getitem(self, idx):
idx = self.df.index.start + idx
Expand Down
19 changes: 13 additions & 6 deletions aperturedb/DescriptorSetDataCSV.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,12 +48,19 @@ class DescriptorSetDataCSV(CSVParser.CSVParser):
def __init__(self, filename, df=None, use_dask=False):

super().__init__(filename, df=df, use_dask=use_dask)
if not use_dask:
self.props_keys = [x for x in self.header[4:]
if not x.startswith(CSVParser.CONSTRAINTS_PREFIX)]
self.constraints_keys = [x for x in self.header[4:]
if x.startswith(CSVParser.CONSTRAINTS_PREFIX)]
self.command = "AddDescriptorSet"

self.props_keys = [x for x in self.header[4:]
if not x.startswith(CSVParser.CONSTRAINTS_PREFIX)]
self.constraints_keys = [x for x in self.header[4:]
if x.startswith(CSVParser.CONSTRAINTS_PREFIX)]
self.command = "AddDescriptorSet"

def get_indices(self):
return {
"entity": {
"_DescriptorSet": self.get_indexed_properties()
}
}

def getitem(self, idx):

Expand Down
19 changes: 13 additions & 6 deletions aperturedb/EntityDataCSV.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,12 +41,19 @@ class EntityDataCSV(CSVParser.CSVParser):

def __init__(self, filename, df=None, use_dask=False):
super().__init__(filename, df=df, use_dask=use_dask)
if not use_dask:
self.props_keys = [x for x in self.header[1:]
if not x.startswith(CSVParser.CONSTRAINTS_PREFIX)]
self.constraints_keys = [x for x in self.header[1:]
if x.startswith(CSVParser.CONSTRAINTS_PREFIX)]
self.command = "AddEntity"

self.props_keys = [x for x in self.header[1:]
if not x.startswith(CSVParser.CONSTRAINTS_PREFIX)]
self.constraints_keys = [x for x in self.header[1:]
if x.startswith(CSVParser.CONSTRAINTS_PREFIX)]
self.command = "AddEntity"

def get_indices(self):
return {
"entity": {
cls: self.get_indexed_properties() for cls in self.df[ENTITY_CLASS].unique()
}
}

def getitem(self, idx):
idx = self.df.index.start + idx
Expand Down
45 changes: 26 additions & 19 deletions aperturedb/ImageDataCSV.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,26 +76,33 @@ def __init__(self, filename, check_image=True, n_download_retries=3, df=None, us
super().__init__(filename, df=df, use_dask=use_dask)

self.check_image = check_image
if not use_dask:
self.format_given = IMG_FORMAT in self.header
self.props_keys = [x for x in self.header[1:]
if not x.startswith(CSVParser.CONSTRAINTS_PREFIX)]
self.props_keys = [
x for x in self.props_keys if x != IMG_FORMAT]
self.constraints_keys = [x for x in self.header[1:]
if x.startswith(CSVParser.CONSTRAINTS_PREFIX)]

self.source_type = self.header[0]

if self.source_type not in self.source_types:
logger.error("Source not recognized: " + self.source_type)
raise Exception("Error loading image: " + filename)
self.source_loader = {
st: sl for st, sl in zip(self.source_types, self.loaders)
}

self.n_download_retries = n_download_retries
self.command = "AddImage"
self.format_given = IMG_FORMAT in self.header
self.props_keys = [x for x in self.header[1:]
if not x.startswith(CSVParser.CONSTRAINTS_PREFIX)]
self.props_keys = [
x for x in self.props_keys if x != IMG_FORMAT]
self.constraints_keys = [x for x in self.header[1:]
if x.startswith(CSVParser.CONSTRAINTS_PREFIX)]

self.source_type = self.header[0]

if self.source_type not in self.source_types:
logger.error("Source not recognized: " + self.source_type)
raise Exception("Error loading image: " + filename)
self.source_loader = {
st: sl for st, sl in zip(self.source_types, self.loaders)
}

self.n_download_retries = n_download_retries
self.command = "AddImage"

def get_indices(self):
return {
"entity": {
"_Image": self.get_indexed_properties()
}
}

def getitem(self, idx):
idx = self.df.index.start + idx
Expand Down
53 changes: 53 additions & 0 deletions aperturedb/ParallelLoader.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,59 @@ def __init__(self, db, dry_run=False):
super().__init__(db, dry_run=dry_run)
self.type = "element"

def get_existing_indices(self):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sorry to join the party late here 🥲

This functionality is pretty much a re-implementation of what we have on our Utils.py file. We should try to re-use those.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I will create an issue for re-factoring this later, it is not a big deal.

schema_result, _ = self.db.query([{"GetSchema": {}}])
schema = schema_result[0]["GetSchema"]
existing_indices = {}
if schema:
for index_type in (("entity", "entities"), ("connection", "connections")):
foo = schema.get(index_type[1]) or {}
bar = foo.get("classes") or {}
for cls_name, cls_schema in bar.items():
props = cls_schema.get("properties") or {}
for prop_name, prop_schema in props.items():
if prop_schema[1]: # indicates property has an index
existing_indices.setdefault(index_type[0], {}).setdefault(
cls_name, set()).add(prop_name)
return existing_indices

def create_indices(self, indices):
if len(indices) == 0:
return

existing_indices = self.get_existing_indices()
new_indices = []
for tp, classes in indices.items():
ex_classes = existing_indices.get(tp, {})
for cls, props in classes.items():
ex_props = ex_classes.get(cls, set())
for prop in props - ex_props:
new_indices.append({
"index_type": tp,
"class": cls,
"property_key": prop
})

if len(new_indices) == 0:
return

logger.info(
f"Creating {len(new_indices)} indices: {new_indices}.")

create_indices = [{"CreateIndex": idx} for idx in new_indices]

res, _ = self.db.query(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same here, we should just use this method on Utils.py.

create_indices)

if self.db.check_status(res) != 0:
logger.warning(
"Failed to create indices; ingestion will be slow.")
logger.warning(res)

def query_setup(self, generator):
if hasattr(generator, "get_indices"):
self.create_indices(generator.get_indices())

def ingest(self, generator, batchsize=1, numthreads=4, stats=False):
logger.info(
f"Starting ingestion with batchsize={batchsize}, numthreads={numthreads}")
Expand Down
7 changes: 6 additions & 1 deletion aperturedb/ParallelQuery.py
Original file line number Diff line number Diff line change
Expand Up @@ -240,10 +240,15 @@ def query(self, generator, batchsize=1, numthreads=4, stats=False):
stats (bool, optional): Show statistics at end of ingestion. Defaults to False.
"""

if hasattr(generator, "use_dask") and generator.use_dask:
use_dask = hasattr(generator, "use_dask") and generator.use_dask
if use_dask:
self._reset(batchsize=batchsize, numthreads=numthreads)
self.daskmanager = DaskManager(num_workers=numthreads)

if hasattr(self, "query_setup"):
self.query_setup(generator)

if use_dask:
results, self.total_actions_time = self.daskmanager.run(
self.db, generator, batchsize, stats=stats)
self.actual_stats = []
Expand Down
3 changes: 2 additions & 1 deletion aperturedb/Parallelizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,8 @@ def run(self, generator, batchsize, numthreads, stats):
a = [th.join() for th in thread_arr]

# Update progress bar to completion
self.pb.update(1)
if self.stats:
self.pb.update(1)

self.total_actions_time = time.time() - start_time

Expand Down
Loading