PanagiotisMark commited on
Commit
5eaf903
·
verified ·
1 Parent(s): 039d674

Update gradio_app.py

Browse files
Files changed (1) hide show
  1. gradio_app.py +43 -43
gradio_app.py CHANGED
@@ -60,7 +60,8 @@ def toggle_feedback(request_data, response_data, like_clicked, dislike_clicked):
60
  else:
61
  return "Feedback sent successfully!"
62
 
63
- def preprocess_and_flatten(json_results, nested_fields, meta_fields=None):
 
64
  # Ensure 'meta_fields' is a list or set default fields
65
  if meta_fields is None:
66
  meta_fields = ['doc_id', 'details', 'domain']
@@ -70,45 +71,44 @@ def preprocess_and_flatten(json_results, nested_fields, meta_fields=None):
70
  print(f"Invalid JSON results: Expected a dictionary but got {type(json_results)}")
71
  return pd.DataFrame() # Return an empty DataFrame if json_results is not a dictionary
72
 
73
- # Preprocess each field in the nested_fields list
74
- for field in nested_fields:
75
- if field in json_results:
76
- nested_field = json_results.get(field)
77
- if isinstance(nested_field, dict):
78
- json_results[field] = [nested_field] # Wrap dict in a list if it's a dict
79
- elif not isinstance(nested_field, list):
80
- json_results[field] = [] # Default to empty list if not a list or dict
81
-
82
- # Flatten the JSON for each field in nested_fields
83
- dataframes = []
84
- for field in nested_fields:
85
- # Check if the field exists in json_results
86
- if field not in json_results or not isinstance(json_results[field], list):
87
- print(f"Field '{field}' not found or is not a list in the JSON results.")
88
- continue # Skip this field if it's missing or not a list
89
-
90
- try:
91
- # Flatten the JSON for the specified nested field
92
- dataframe_results = pd.json_normalize(
93
- json_results,
94
- record_path=[field], # Nested array to flatten
95
- meta=meta_fields, # Top-level fields to retain
96
- sep='_', # Separator for nested fields
97
- errors='ignore' # To handle cases with missing keys
98
- )
99
- if not dataframe_results.empty:
100
- dataframes.append(dataframe_results) # Append the flattened DataFrame
101
- except Exception as e:
102
- print(f"Error while flattening field '{field}': {e}")
103
- continue # Skip this field if an error occurs
104
-
105
- # Concatenate all the DataFrames if there are any
106
- if dataframes:
107
- final_dataframe = pd.concat(dataframes, ignore_index=True)
108
- else:
109
- final_dataframe = pd.DataFrame() # Return an empty DataFrame if nothing was flattened
110
-
111
- return final_dataframe
112
 
113
  # Define the functions to handle the inputs and outputs
114
  def news_analysis(text):
@@ -126,7 +126,7 @@ def news_analysis(text):
126
  # Prepare results for JSON output
127
  json_results = response.json()
128
  # Flatten 'claim_objects' field
129
- dataframe_results = preprocess_and_flatten(json_results, ['claim_objects'], ['doc_id', 'details', 'domain'])
130
  return json_results, dataframe_results
131
  except Exception as e:
132
  results = {'error': str(e)}
@@ -146,8 +146,8 @@ def claim_verification(text):
146
  response.raise_for_status()
147
  # Prepare results for JSON output
148
  json_results = response.json()
149
- # Call preprocess_and_flatten to flatten 'support', 'refute', and 'no_info' fields
150
- dataframe_results = preprocess_and_flatten(json_results, ['support', 'refute', 'no_info'], ['doc_id', 'details'])
151
  return json_results, dataframe_results
152
  except Exception as e:
153
  results = {'error': str(e)}
 
60
  else:
61
  return "Feedback sent successfully!"
62
 
63
+
64
+ def preprocess_and_flatten(json_results, mode, meta_fields=None):
65
  # Ensure 'meta_fields' is a list or set default fields
66
  if meta_fields is None:
67
  meta_fields = ['doc_id', 'details', 'domain']
 
71
  print(f"Invalid JSON results: Expected a dictionary but got {type(json_results)}")
72
  return pd.DataFrame() # Return an empty DataFrame if json_results is not a dictionary
73
 
74
+ # Collect flattened data
75
+ flattened_data = []
76
+
77
+ # Mode-based logic
78
+ if mode == 'news_analysis':
79
+ # Handle 'claim_objects' for news analysis mode
80
+ claim_objects = json_results.get('claim_objects', [])
81
+ if isinstance(claim_objects, list):
82
+ for item in claim_objects:
83
+ flattened_data.append({
84
+ 'doc_id': json_results.get('doc_id'),
85
+ 'details': json_results.get('details'),
86
+ 'domain': json_results.get('domain'),
87
+ 'topic': item.get('topic', ''),
88
+ 'claim': item.get('claim', ''),
89
+ 'claimer': item.get('claimer', '')
90
+ })
91
+
92
+ elif mode == 'claim_verification':
93
+ # Handle 'support', 'refute', 'no_info' for claim verification mode
94
+ nested_fields = ['support', 'refute', 'no_info']
95
+ for field in nested_fields:
96
+ nested_items = json_results.get(field, [])
97
+ if not isinstance(nested_items, list):
98
+ continue
99
+
100
+ # Loop over each item in the nested field and flatten
101
+ for item in nested_items:
102
+ flattened_data.append({
103
+ 'doc_id': json_results.get('doc_id'),
104
+ 'details': json_results.get('details'),
105
+ 'category': field, # Mark which category the item belongs to (support/refute/no_info)
106
+ 'sentence': item.get('sentence', ''),
107
+ 'doi': item.get('doi', '')
108
+ })
109
+
110
+ # Convert to DataFrame
111
+ return pd.DataFrame(flattened_data)
 
112
 
113
  # Define the functions to handle the inputs and outputs
114
  def news_analysis(text):
 
126
  # Prepare results for JSON output
127
  json_results = response.json()
128
  # Flatten 'claim_objects' field
129
+ dataframe_results = preprocess_and_flatten(json_results, mode='news_analysis')
130
  return json_results, dataframe_results
131
  except Exception as e:
132
  results = {'error': str(e)}
 
146
  response.raise_for_status()
147
  # Prepare results for JSON output
148
  json_results = response.json()
149
+ # Flatten 'support', 'refute', and 'no_info' fields
150
+ dataframe_results = preprocess_and_flatten(json_results, mode='claim_verification')
151
  return json_results, dataframe_results
152
  except Exception as e:
153
  results = {'error': str(e)}