quoc-khanh commited on
Commit
305f520
·
verified ·
1 Parent(s): e1f2fad

Update helpers.py

Browse files
Files changed (1) hide show
  1. helpers.py +15 -6
helpers.py CHANGED
@@ -146,15 +146,18 @@ key = os.getenv("GOOGLE_API_KEY")
146
  # new_metadata = None
147
  # return new_metadata
148
 
149
- def extract_metadata(response_string):
 
 
 
150
  # Tìm tất cả các dictionary trong chuỗi đầu vào
151
- matches = re.findall(r'\{.*?\}', response_string, re.DOTALL)
152
  if not matches:
153
- return None
154
-
155
  smallest_dict = None
156
  min_length = float("inf")
157
-
158
  for match in matches:
159
  try:
160
  parsed_dict = ast.literal_eval(match) # Chuyển đổi string thành dictionary
@@ -165,9 +168,15 @@ def extract_metadata(response_string):
165
  min_length = dict_length
166
  except Exception:
167
  continue # Bỏ qua nếu không phải dictionary hợp lệ
168
-
169
  return smallest_dict
170
 
 
 
 
 
 
 
171
  # # Example usage:
172
  # input_str = "Some random text before and then {'a': 'abc', 'b': 'bcd'} and some random text after."
173
  # metadata = extract_metadata(input_str)
 
146
  # new_metadata = None
147
  # return new_metadata
148
 
149
+ def extract_metadata(response):
150
+ if not isinstance(response, str):
151
+ response = str(response) # Chuyển sang string nếu cần
152
+
153
  # Tìm tất cả các dictionary trong chuỗi đầu vào
154
+ matches = re.findall(r'\{.*?\}', response, re.DOTALL)
155
  if not matches:
156
+ return None # Trả về None nếu không tìm thấy dict nào
157
+
158
  smallest_dict = None
159
  min_length = float("inf")
160
+
161
  for match in matches:
162
  try:
163
  parsed_dict = ast.literal_eval(match) # Chuyển đổi string thành dictionary
 
168
  min_length = dict_length
169
  except Exception:
170
  continue # Bỏ qua nếu không phải dictionary hợp lệ
171
+
172
  return smallest_dict
173
 
174
+ # 🛠 **Ví dụ sử dụng**
175
+ response = None # Hoặc một object không phải string
176
+ smallest_dict = extract_smallest_dict(response)
177
+ print(smallest_dict) # Output: None
178
+
179
+
180
  # # Example usage:
181
  # input_str = "Some random text before and then {'a': 'abc', 'b': 'bcd'} and some random text after."
182
  # metadata = extract_metadata(input_str)