Skip to content
Merged
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
76 changes: 38 additions & 38 deletions src/turninator.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,46 +67,46 @@ def get_aif_(self, format='xAIF'):
return json.dumps(aif)

def get_aif(self, format='xAIF'):
"""
This function reads the file, processes it, and returns the xAIF or AIF section in the correct format.
If the input file format is not valid, it attempts to correct it and then returns the desired format.
"""
try:
# Open the file and read its contents
with open(self.f_name, 'r') as file:
data = file.read()

# Try to load the data as JSON
try:
x_aif = json.loads(data)
except JSONDecodeError as e:
logging.error(f"Error decoding JSON: {e}")
return {"error": "Invalid JSON format"}

# Ensure x_aif is a dictionary, handle if it's a string
if isinstance(x_aif, str):
with open(self.f_name) as file:
data = file.read()

# Check if the file content is a valid JSON string (it might be a JSON object or an array)
try:
data = json.loads(data) # Try to load it as a JSON object
except ValueError as e:
print(f"Error decoding JSON from file: {e}")
return None

# Function to handle string entries (decoding double escaping if needed)
def process_data(entry):
if isinstance(entry, str):
try:
x_aif = json.loads(x_aif) # Try to load it again if it's a string
except JSONDecodeError as e:
logging.error(f"Error re-decoding JSON: {e}")
return {"error": "Invalid JSON format after re-processing string"}

# If format is "xAIF", return the whole xAIF structure
if format == "xAIF":
return json.dumps(x_aif)

# Otherwise, extract the 'aif' section, if available
aif = x_aif.get('aif')
if not aif:
logging.warning("The 'aif' section is missing from the input JSON.")
return {"error": "'aif' section is missing"}

# Try to decode the string if it's double-escaped JSON
decoded = json.loads(entry)
return decoded
except ValueError:
# If decoding fails, return the string as-is
return entry
elif isinstance(entry, dict):
# Process each key-value pair in the dictionary
for key, value in entry.items():
entry[key] = process_data(value)
elif isinstance(entry, list):
# Process each item in the list
for index, item in enumerate(entry):
entry[index] = process_data(item)
return entry

# Process the entire data structure (file contents)
data = process_data(data)

# Convert the processed data back to JSON string if necessary
if format == "xAIF":
return json.dumps(data)
else:
# Extract 'aif' section from the data, if it exists
aif = data.get('aif', data)
return json.dumps(aif)

except Exception as e:
logging.error(f"An error occurred while processing the file: {e}")
return {"error": "Unexpected error occurred while processing the file"}

def turninator_default(self,):
# Get the file path from the path object

Expand Down
Loading