Skip to content

Commit

Permalink
remove a table output (#549)
Browse files Browse the repository at this point in the history
  • Loading branch information
Josef-Haupt authored Jan 28, 2025
1 parent ce6f494 commit ed6d485
Show file tree
Hide file tree
Showing 4 changed files with 97 additions and 97 deletions.
152 changes: 76 additions & 76 deletions birdnet_analyzer/analyze.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,50 +176,50 @@ def generate_audacity(timestamps: list[str], result: dict[str, list], result_pat
utils.save_result_file(result_path, out_string)


def generate_rtable(timestamps: list[str], result: dict[str, list], afile_path: str, result_path: str):
"""
Generates a R table string from the given timestamps and result data, and saves it to a file.
Args:
timestamps (list[str]): A list of timestamp strings in the format "start-end".
result (dict[str, list]): A dictionary where keys are timestamp strings and values are lists of tuples containing
classification results (label, confidence).
afile_path (str): The path to the audio file being analyzed.
result_path (str): The path where the result table file will be saved.
Returns:
None
"""
out_string = RTABLE_HEADER

for timestamp in timestamps:
rstring = ""
start, end = timestamp.split("-", 1)

for c in result[timestamp]:
if c[1] > cfg.MIN_CONFIDENCE and (not cfg.SPECIES_LIST or c[0] in cfg.SPECIES_LIST):
label = cfg.TRANSLATED_LABELS[cfg.LABELS.index(c[0])]
rstring += "{},{},{},{},{},{:.4f},{:.4f},{:.4f},{},{},{},{},{},{}\n".format(
afile_path,
start,
end,
label.split("_", 1)[0],
label.split("_", 1)[-1],
c[1],
cfg.LATITUDE,
cfg.LONGITUDE,
cfg.WEEK,
cfg.SIG_OVERLAP,
(1.0 - cfg.SIGMOID_SENSITIVITY) + 1.0,
cfg.MIN_CONFIDENCE,
cfg.SPECIES_LIST_FILE,
os.path.basename(cfg.MODEL_PATH),
)

# Write result string to file
out_string += rstring

utils.save_result_file(result_path, out_string)
# def generate_rtable(timestamps: list[str], result: dict[str, list], afile_path: str, result_path: str):
# """
# Generates a R table string from the given timestamps and result data, and saves it to a file.

# Args:
# timestamps (list[str]): A list of timestamp strings in the format "start-end".
# result (dict[str, list]): A dictionary where keys are timestamp strings and values are lists of tuples containing
# classification results (label, confidence).
# afile_path (str): The path to the audio file being analyzed.
# result_path (str): The path where the result table file will be saved.

# Returns:
# None
# """
# out_string = RTABLE_HEADER

# for timestamp in timestamps:
# rstring = ""
# start, end = timestamp.split("-", 1)

# for c in result[timestamp]:
# if c[1] > cfg.MIN_CONFIDENCE and (not cfg.SPECIES_LIST or c[0] in cfg.SPECIES_LIST):
# label = cfg.TRANSLATED_LABELS[cfg.LABELS.index(c[0])]
# rstring += "{},{},{},{},{},{:.4f},{:.4f},{:.4f},{},{},{},{},{},{}\n".format(
# afile_path,
# start,
# end,
# label.split("_", 1)[0],
# label.split("_", 1)[-1],
# c[1],
# cfg.LATITUDE,
# cfg.LONGITUDE,
# cfg.WEEK,
# cfg.SIG_OVERLAP,
# (1.0 - cfg.SIGMOID_SENSITIVITY) + 1.0,
# cfg.MIN_CONFIDENCE,
# cfg.SPECIES_LIST_FILE,
# os.path.basename(cfg.MODEL_PATH),
# )

# # Write result string to file
# out_string += rstring

# utils.save_result_file(result_path, out_string)


def generate_kaleidoscope(timestamps: list[str], result: dict[str, list], afile_path: str, result_path: str):
Expand Down Expand Up @@ -326,8 +326,8 @@ def saveResultFiles(r: dict[str, list], result_files: dict[str, str], afile_path
if "audacity" in cfg.RESULT_TYPES:
generate_audacity(timestamps, r, result_files["audacity"])

if "r" in cfg.RESULT_TYPES:
generate_rtable(timestamps, r, afile_path, result_files["r"])
# if "r" in cfg.RESULT_TYPES:
# generate_rtable(timestamps, r, afile_path, result_files["r"])

if "kaleidoscope" in cfg.RESULT_TYPES:
generate_kaleidoscope(timestamps, r, afile_path, result_files["kaleidoscope"])
Expand Down Expand Up @@ -406,36 +406,36 @@ def combine_raven_tables(saved_results: list[str]):
f.writelines((f + "\n" for f in audiofiles))


def combine_rtable_files(saved_results: list[str]):
"""
Combines multiple R table files into a single file.
# def combine_rtable_files(saved_results: list[str]):
# """
# Combines multiple R table files into a single file.

Args:
saved_results (list[str]): A list of file paths to the result table files to be combined.
# Args:
# saved_results (list[str]): A list of file paths to the result table files to be combined.

Returns:
None
"""
# Combine all files
with open(os.path.join(cfg.OUTPUT_PATH, cfg.OUTPUT_RTABLE_FILENAME), "w", encoding="utf-8") as f:
f.write(RTABLE_HEADER)
# Returns:
# None
# """
# # Combine all files
# with open(os.path.join(cfg.OUTPUT_PATH, cfg.OUTPUT_RTABLE_FILENAME), "w", encoding="utf-8") as f:
# f.write(RTABLE_HEADER)

for rfile in saved_results:
with open(rfile, "r", encoding="utf-8") as rf:
try:
lines = rf.readlines()
# for rfile in saved_results:
# with open(rfile, "r", encoding="utf-8") as rf:
# try:
# lines = rf.readlines()

# make sure it's a selection table
if "filepath" not in lines[0] or "model" not in lines[0]:
continue
# # make sure it's a selection table
# if "filepath" not in lines[0] or "model" not in lines[0]:
# continue

# skip header and add to file
for line in lines[1:]:
f.write(line)
# # skip header and add to file
# for line in lines[1:]:
# f.write(line)

except Exception as ex:
print(f"Error: Cannot combine results from {rfile}.\n", flush=True)
utils.writeErrorLog(ex)
# except Exception as ex:
# print(f"Error: Cannot combine results from {rfile}.\n", flush=True)
# utils.writeErrorLog(ex)


def combine_kaleidoscope_files(saved_results: list[str]):
Expand Down Expand Up @@ -516,8 +516,8 @@ def combineResults(saved_results: list[dict[str, str]]):
if "table" in cfg.RESULT_TYPES:
combine_raven_tables([f["table"] for f in saved_results if f])

if "r" in cfg.RESULT_TYPES:
combine_rtable_files([f["r"] for f in saved_results if f])
# if "r" in cfg.RESULT_TYPES:
# combine_rtable_files([f["r"] for f in saved_results if f])

if "kaleidoscope" in cfg.RESULT_TYPES:
combine_kaleidoscope_files([f["kaleidoscope"] for f in saved_results if f])
Expand Down Expand Up @@ -602,8 +602,8 @@ def get_result_file_names(fpath: str):
result_names["table"] = os.path.join(cfg.OUTPUT_PATH, file_shorthand + ".BirdNET.selection.table.txt")
if "audacity" in cfg.RESULT_TYPES:
result_names["audacity"] = os.path.join(cfg.OUTPUT_PATH, file_shorthand + ".BirdNET.results.txt")
if "r" in cfg.RESULT_TYPES:
result_names["r"] = os.path.join(cfg.OUTPUT_PATH, file_shorthand + ".BirdNET.results.r.csv")
# if "r" in cfg.RESULT_TYPES:
# result_names["r"] = os.path.join(cfg.OUTPUT_PATH, file_shorthand + ".BirdNET.results.r.csv")
if "kaleidoscope" in cfg.RESULT_TYPES:
result_names["kaleidoscope"] = os.path.join(
cfg.OUTPUT_PATH, file_shorthand + ".BirdNET.results.kaleidoscope.csv"
Expand Down Expand Up @@ -777,9 +777,9 @@ def __call__(self, parser, args, values, option_string=None):
parser.add_argument(
"--rtype",
default={"table"},
choices=["table", "audacity", "r", "kaleidoscope", "csv"],
choices=["table", "audacity", "kaleidoscope", "csv"],
nargs="+",
help="Specifies output format. Values in ['table', 'audacity', 'r', 'kaleidoscope', 'csv']. Defaults to 'table' (Raven selection table).",
help="Specifies output format. Values in ['table', 'audacity', 'kaleidoscope', 'csv']. Defaults to 'table' (Raven selection table).",
action=UniqueSetAction,
)
parser.add_argument(
Expand Down
2 changes: 1 addition & 1 deletion birdnet_analyzer/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@
# 'csv' denotes a generic CSV file with start, end, species and confidence.
RESULT_TYPES: set[str] | list[str] = {"table"}
OUTPUT_RAVEN_FILENAME: str = "BirdNET_SelectionTable.txt" # this is for combined Raven selection tables only
OUTPUT_RTABLE_FILENAME: str = "BirdNET_RTable.csv"
# OUTPUT_RTABLE_FILENAME: str = "BirdNET_RTable.csv"
OUTPUT_KALEIDOSCOPE_FILENAME: str = "BirdNET_Kaleidoscope.csv"
OUTPUT_CSV_FILENAME: str = "BirdNET_CombinedTable.csv"

Expand Down
2 changes: 1 addition & 1 deletion birdnet_analyzer/gui/multi_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
OUTPUT_TYPE_MAP = {
"Raven selection table": "table",
"Audacity": "audacity",
"R": "r",
# "R": "r",
"CSV": "csv",
"Kaleidoscope": "kaleidoscope",
}
Expand Down
38 changes: 19 additions & 19 deletions birdnet_analyzer/segments.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,12 @@ def detectRType(line: str):
line: First line of text.
Returns:
Either "table", "r", "kaleidoscope", "csv" or "audacity".
Either "table", "kaleidoscope", "csv" or "audacity".
"""
if line.lower().startswith("selection"):
return "table"
elif line.lower().startswith("filepath"):
return "r"
# elif line.lower().startswith("filepath"):
# return "r"
elif line.lower().startswith("indir"):
return "kaleidoscope"
elif line.lower().startswith("start (s)"):
Expand Down Expand Up @@ -93,9 +93,9 @@ def parseFolders(apath: str, rpath: str, allowed_result_filetypes: list[str] = [
elif os.path.exists(os.path.join(rpath, cfg.OUTPUT_KALEIDOSCOPE_FILENAME)):
rfile = os.path.join(rpath, cfg.OUTPUT_KALEIDOSCOPE_FILENAME)
data["combined"] = {"isCombinedFile": True, "result": rfile}
elif os.path.exists(os.path.join(rpath, cfg.OUTPUT_RTABLE_FILENAME)):
rfile = os.path.join(rpath, cfg.OUTPUT_RTABLE_FILENAME)
data["combined"] = {"isCombinedFile": True, "result": rfile}
# elif os.path.exists(os.path.join(rpath, cfg.OUTPUT_RTABLE_FILENAME)):
# rfile = os.path.join(rpath, cfg.OUTPUT_RTABLE_FILENAME)
# data["combined"] = {"isCombinedFile": True, "result": rfile}
else:
# Get all audio files
for root, _, files in os.walk(apath):
Expand Down Expand Up @@ -236,13 +236,13 @@ def findSegmentsFromCombined(rfile: str) -> list[dict]:
confidence = float(d[header_mapping["Confidence"]])
afile = d[header_mapping["Begin Path"]].replace("/", os.sep).replace("\\", os.sep)

elif rtype == "r" and i > 0:
d = line.split(",")
start = float(d[header_mapping["start"]])
end = float(d[header_mapping["end"]])
species = d[header_mapping["common_name"]]
confidence = float(d[header_mapping["confidence"]])
afile = d[header_mapping["filepath"]].replace("/", os.sep).replace("\\", os.sep)
# elif rtype == "r" and i > 0:
# d = line.split(",")
# start = float(d[header_mapping["start"]])
# end = float(d[header_mapping["end"]])
# species = d[header_mapping["common_name"]]
# confidence = float(d[header_mapping["confidence"]])
# afile = d[header_mapping["filepath"]].replace("/", os.sep).replace("\\", os.sep)

elif rtype == "kaleidoscope" and i > 0:
d = line.split(",")
Expand Down Expand Up @@ -312,12 +312,12 @@ def findSegments(afile: str, rfile: str):
species = d[2].split(", ")[1]
confidence = float(d[-1])

elif rtype == "r" and i > 0:
d = line.split(",")
start = float(d[header_mapping["start"]])
end = float(d[header_mapping["end"]])
species = d[header_mapping["common_name"]]
confidence = float(d[header_mapping["confidence"]])
# elif rtype == "r" and i > 0:
# d = line.split(",")
# start = float(d[header_mapping["start"]])
# end = float(d[header_mapping["end"]])
# species = d[header_mapping["common_name"]]
# confidence = float(d[header_mapping["confidence"]])

elif rtype == "kaleidoscope" and i > 0:
d = line.split(",")
Expand Down

0 comments on commit ed6d485

Please sign in to comment.