Skip to content

Commit b2f6efe

Browse files
author
Sean Smith
committed
Changed logic od DataFrame parsing
Signed-off-by: Sean Smith <sean.smith@contextual.ai>
1 parent c8684a0 commit b2f6efe

File tree

1 file changed

+25
-7
lines changed

1 file changed

+25
-7
lines changed

src/contextual/_response.py

Lines changed: 25 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -501,21 +501,39 @@ def to_dataframe(self) -> DataFrame:
501501
for line in lines:
502502
try:
503503
entry = json.loads(line)
504-
# Parse the results string if it exists
505-
if "results" in entry:
506-
results = ast.literal_eval(entry["results"])
507-
del entry["results"]
504+
# Parse the results field directly from JSON
505+
if 'results' in entry:
506+
if isinstance(entry['results'], str):
507+
# Try to handle string representations that are valid JSON
508+
try:
509+
results = json.loads(entry['results'])
510+
except Exception as e:
511+
# If not valid JSON, fall back to safer processing
512+
results = ast.literal_eval(entry['results'])
513+
else:
514+
# Already a dictionary
515+
results = entry['results']
516+
517+
# Remove the original results field
518+
del entry['results']
519+
# Flatten the nested dictionary structure
508520
if isinstance(results, dict):
509521
for key, value in results.items(): # type: ignore
510522
if isinstance(value, dict):
511523
for subkey, subvalue in value.items(): # type: ignore
512-
entry[f"{key}_{subkey}"] = subvalue
524+
if isinstance(subvalue, dict):
525+
# Handle one more level of nesting
526+
for subsubkey, subsubvalue in subvalue.items(): # type: ignore
527+
entry[f'{key}_{subkey}_{subsubkey}'] = subsubvalue
528+
else:
529+
entry[f'{key}_{subkey}'] = subvalue
513530
else:
514531
entry[key] = value
515532

516-
data.append(entry) # type: ignore
533+
data.append(entry) # type: ignore
517534
except Exception as e:
518-
log.info(f"Error processing line: {e}")
535+
log.error(f"Error processing line: {e}")
536+
log.error(f"Problematic line: {line[:200]}...") # Print first 200 chars of the line
519537
continue
520538
return DataFrame(data)
521539

0 commit comments

Comments
 (0)