# import sys

# def read_input():
#     input = sys.stdin.read
#     data = input().split()
#     return data

# data = read_input()
# index = 0
# t = int(data[index])
# index += 1

# results = []

# for _ in range(t):
#     n = int(data[index])
#     index += 1
#     words = data[index:index + n]
#     index += n
    
#     start_with_0, start_with_1 = set(), set()

#     for i, word in enumerate(words):
#         if word[0] == '0':
#             start_with_0.add((word, i + 1))
#         else:
#             start_with_1.add((word, i + 1))
    
#     count_01, count_10 = 0, 0
#     for word, _ in start_with_0:
#         if word[-1] == '1':
#             count_01 += 1
#     for word, _ in start_with_1:
#         if word[-1] == '0':
#             count_10 += 1
    
#     if count_01 > 0 and count_10 > 0:
#         if abs(count_01 - count_10) % 2 != 0:
#             results.append("-1")
#             continue

#         to_reverse = set()
#         need_to_reverse = abs(count_01 - count_10) // 2

#         if count_01 > count_10:
#             target_set = start_with_0
#             end_char = '1'
#         else:
#             target_set = start_with_1
#             end_char = '0'

#         reversed_count = 0

#         for word, idx in target_set:
#             if reversed_count >= need_to_reverse:
#                 break
#             if word[-1] == end_char:
#                 to_reverse.add(idx)
#                 reversed_count += 1

#         results.append(f"{len(to_reverse)}")
#         if len(to_reverse) > 0:
#             results.append(" ".join(map(str, sorted(to_reverse))))
        
#     else:
#         results.append("0")

# sys.stdout.write("\n".join(results) + "\n")



import json
import re
def extract_patch_from_json(patchs):
    # 正则匹配 ```json\n ... \n``` 之间的内容（不含首尾空行）
    match = re.search(r"```json\s*(\{.*?\})\s*```", patchs, re.DOTALL)
    return match.group(1).strip() if match else ""


def main(patches_json) -> dict:
    
    # data = json.loads(patches_json)
    data = patches_json
    text = data['text']

    # 从文本中提取JSON部分（在 { 和 } 之间的内容）
    import re
    # 找到第一个 { 和最后一个 } 之间的内容
    json_match = re.search(r'\{.*\}', text, re.DOTALL)
    
    if json_match:
        json_str = json_match.group(0)
        try:
            text_dict = json.loads(json_str)
            final_patch = text_dict['final_patch']
            patch = final_patch['patch']
            return {'result': patch}
        except json.JSONDecodeError as e:
            print(f"JSON解析错误: {e}")
            return {'result': text}
    else:
        # 如果没有找到JSON格式的内容，直接返回text
        return {'result': text}
        
    


{
  "text": "diff --git a/astropy/modeling/separable.py b/astropy/modeling/separable.py\nindex 1234567..fedcba9 100644\n--- a/astropy/modeling/separable.py\n+++ b/astropy/modeling/separable.py\n@@ -1,3 +1,8 @@\n+def _collect_io_mappings(model):\n+    if not isinstance(model, CompoundModel):\n+        return [(model.inputs, model.outputs)]\n+    else:\n+        return _collect_io_mappings(model.left) + _collect_io_mappings(model.right)\n+\n def separability_matrix(model):\n-    inputs, outputs = _get_model_inputs_outputs(model)\n-    submodels = _traverse_model_graph(model)\n+    io_mappings = _collect_io_mappings(model)\n+    inputs = []\n+    outputs = []\n+    for ins, outs in io_mappings:\n+        inputs.extend(ins)\n+        outputs.extend(outs)\n \n     matrix = np.zeros((len(outputs), len(inputs)), dtype=bool)\n \n-    for m in submodels:\n-        for o in m.outputs:\n-            for i in m.inputs:\n+    for ins, outs in io_mappings:\n+        for o in outs:\n+            for i in ins:\n                 matrix[outputs.index(o), inputs.index(i)] = True\n \n     return matrix",
  "usage": {
    "prompt_tokens": 4633,
    "prompt_unit_price": "3",
    "prompt_price_unit": "0.000001",
    "prompt_price": "0.013899",
    "completion_tokens": 376,
    "completion_unit_price": "15",
    "completion_price_unit": "0.000001",
    "completion_price": "0.00564",
    "total_tokens": 5009,
    "total_price": "0.019539",
    "currency": "USD",
    "latency": 6.334269293991383
  },
  "finish_reason": "end_turn",
  "files": []
}

# 运行测试
result = main(patches_json)
print("提取的patch内容:")
print(result['result'])
