Upload 2 files
Browse filesFiles changed (2)
- json_parse.pyAdded+147
- process.pyAdded+48
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147import json
import re
def _replace_new_line(match: re.Match[str]) -> str:
value = match.group(2)
value = re.sub(r"\n", r"\\n", value)
value = re.sub(r"\r", r"\\r", value)
value = re.sub(r"\t", r"\\t", value)
value = re.sub(r'(?<!\\)"', r"\"", value)
return match.group(1) + value + match.group(3)
def _custom_parser(multiline_string: str) -> str:
"""
The LLM response for `action_input` may be a multiline
string containing unescaped newlines, tabs or quotes. This function
replaces those characters with their escaped counterparts.
(newlines in JSON must be double-escaped: `\\n`)
"""
if isinstance(multiline_string, (bytes, bytearray)):
multiline_string = multiline_string.decode()
multiline_string = re.sub(
r'("action_input"\:\s*")(.*?)(")',
_replace_new_line,
multiline_string,
flags=re.DOTALL,
)
return multiline_string
def parse_partial_json(s: str, *, strict: bool = False):
"""Parse a JSON string that may be missing closing braces.
Args:
s: The JSON string to parse.
strict: Whether to use strict parsing. Defaults to False.
Returns:
The parsed JSON object as a Python dictionary.
"""
# Attempt to parse the string as-is.
try:
return json.loads(s, strict=strict)
except json.JSONDecodeError:
pass
# Initialize variables.
new_s = ""
stack = []
is_inside_string = False
escaped = False
# Process each character in the string one at a time.
for char in s:
if is_inside_string:
if char == '"' and not escaped:
is_inside_string = False
elif char == "\n" and not escaped:
char = "\\n" # Replace the newline character with the escape sequence.
elif char == "\\":
escaped = not escaped
else:
escaped = False
else:
if char == '"':
is_inside_string = True
escaped = False
elif char == "{":
stack.append("}")
elif char == "[":
stack.append("]")
elif char == "}" or char == "]":
if stack and stack[-1] == char:
stack.pop()
else:
# Mismatched closing character; the input is malformed.
return None
# Append the processed character to the new string.
new_s += char
# If we're still inside a string at the end of processing,
# we need to close the string.
if is_inside_string:
new_s += '"'
# Try to parse mods of string until we succeed or run out of characters.
while new_s:
final_s = new_s
# Close any remaining open structures in the reverse
# order that they were opened.
for closing_char in reversed(stack):
final_s += closing_char
# Attempt to parse the modified string as JSON.
try:
return json.loads(final_s, strict=strict)
except json.JSONDecodeError:
# If we still can't parse the string as JSON,
# try removing the last character
new_s = new_s[:-1]
# If we got here, we ran out of characters to remove
# and still couldn't parse the string as JSON, so return the parse error
# for the original string.
return json.loads(s, strict=strict)
def main(
json_string: str
) -> dict:
"""
Parse a JSON string from a Markdown string.
Args:
json_string: The Markdown string.
Returns:
The parsed JSON object as a Python dictionary.
"""
try:
# Try to find JSON string within triple backticks
match = re.search(r"```(json)?(.*)", json_string, re.DOTALL)
# If no match found, assume the entire string is a JSON string
if match is None:
json_str = json_string
else:
# If match found, use the content within the backticks
json_str = match.group(2)
# Strip whitespace and newlines from the start and end
json_str = json_str.strip().strip("`")
# handle newlines and other special characters inside the returned value
json_str = _custom_parser(json_str)
# Parse the JSON string into a Python dictionary
parsed = parse_partial_json(json_str)
return parsed
except Exception as e:
print(e)
return {
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748import json
def process_jsonl(input_file, success_file, failure_file): success_list = [] failure_list = [] with open(input_file, 'r', encoding='utf-8') as infile: for line in infile: line = line.strip() if not line: continue try: data = json.loads(line) except json.JSONDecodeError: # 如果整行不是有效的JSON,直接加入失败列表 failure_list.append(line) continue result_str = data.get('result', '') # 去除“```json”开头和“```”结尾 if result_str.startswith("```json"): result_str = result_str[len("```json"):].lstrip() if result_str.endswith("```"): result_str = result_str[:-len("```")].rstrip() # 去除转义字符和换行符 # 替换转义的双引号和反斜杠 result_str = result_str.replace('\\"', '"').replace('\\\\', '\\') result_str = result_str.replace('\\n', '') # 现在尝试解析为JSON try: result_json = json.loads(result_str) # 确保 result_json 是一个列表 if not isinstance(result_json, list): result_json = [result_json] data['result'] = result_json success_list.append(data) except json.JSONDecodeError as e: # 解析失败,将原始的line加入失败列表 failure_list.append(line) # 写入成功数据 with open(success_file, 'w', encoding='utf-8') as sf: for item in success_list: sf.write(json.dumps(item, ensure_ascii=False) + '\n') # 写入失败数据 with open(failure_file, 'w', encoding='utf-8') as ff: for item in failure_list: ff.write(item + '\n')
# 调用函数process_jsonl('gpt4_query_correlation2.jsonl', 'success.jsonl', 'failure.jsonl')json_parse.pyAdded+147
process.pyAdded+48