分析下面的代码 主要是解析pdf 然后将pdf的文本内容翻译 然后 将翻译的结果再次写入到pdf中
group_spans_into_lines是判断是否是处于同一行的函数 这里需要增加一个条件 就是 字体size需要相同才可以归为同一行 帮我修改下group_spans_into_lines代码


 def extract_text_and_layout(self, pdf_path, output_pdf, inside_text=False):

        input_doc = fitz.open(pdf_path)
        total_pages = input_doc.page_count
        font_list = []
        self.pagesAllSignal.emit(total_pages)
        output_doc = fitz.open()

        # 定义一个函数来根据 bbox[1] 值将 spans 分组到同一行
        def group_spans_into_lines(spans_list, y_tolerance=1.0):
            """
            将 spans 根据 y 坐标（bbox[1]）分组到同一行
            :param spans_list: spans 的列表
            :param y_tolerance: 在 y 轴上的容差，用于判断是否在同一行
            :return: lines 的列表，每个 line 是 spans 的列表
            """
            # 按照 y 坐标（bbox[1]）排序 spans
            spans_list_sorted = sorted(spans_list, key=lambda s: s['bbox'][1])
            lines = []
            current_line = []
            last_y = None
            for span in spans_list_sorted:
                y = span['bbox'][1]
                if last_y is None or abs(y - last_y) > y_tolerance:
                    # 开始新的一行
                    if current_line:
                        lines.append(current_line)
                    current_line = [span]
                    last_y = y
                else:
                    current_line.append(span)
            # 添加最后一行
            if current_line:
                lines.append(current_line)
            return lines

        for i, page in enumerate(input_doc):
            self.PageSignal.emit(i + 1)
            pix = page.get_pixmap()
            self.renderImage.emit(pix)
            pages_info = []
            page_blocks = page.get_text("dict")["blocks"]
            blocks_info = []
            # 用于统计字体大小
            font_size_count = defaultdict(int)
            total_text_length = 0

            for block in page_blocks:
                if block["type"] == 0:  # 文本块
                    spans_list = []
                    # 收集所有的 spans
                    for line in block["lines"]:
                        for span in line["spans"]:
                            spans_list.append(span)
                    # 使用自定义函数将 spans 分组到同一行
                    grouped_lines = group_spans_into_lines(spans_list)
                    lines_info = []
                    for spans_in_line in grouped_lines:
                        spans_info = []
                        for span in spans_in_line:
                            text = span["text"]
                            if span["font"] not in font_list:
                                font_list.append(span["font"])
                            # 统计字体大小
                            # 计算整行的 bbox
                            x0 = min(s['bbox'][0] for s in spans_in_line)
                            y0 = min(s['bbox'][1] for s in spans_in_line)
                            x1 = min(s['bbox'][2] for s in spans_in_line)
                            y1 = max(s['bbox'][3] for s in spans_in_line)
                            line_bbox = [x0, y0, x1, y1]
                            font_size_count[span["size"]] += len(text)
                            total_text_length += len(text)
                            spans_info.append({
                                "text": text,
                                "size": span["size"],
                                "color": fitz.sRGB_to_rgb(span["color"]),
                                "bbox": line_bbox,
                                'ascender': span['ascender'],
                                'descender': span['descender'],
                                'origin': span['origin'],
                                "font": span["font"]  # 添加字体信息
                            })

                        lines_info.append({
                            "spans": spans_info,
                            # "bbox": line_bbox
                        })
                    blocks_info.append({
                        "type": 0,
                        "lines": lines_info,
                        "bbox": block["bbox"]
                    })
                else:
                    blocks_info.append(block)

            pages_info.append({
                "blocks": blocks_info
            })
            # 确定小字体的阈值
            sorted_sizes = sorted(font_size_count.keys())
            cumulative_length = 0
            if len(sorted_sizes) < 1:
                small_font_threshold = 10
            else:
                small_font_threshold = sorted_sizes[-1]  # 默认最大的字体大小为阈值
            for size in sorted_sizes:
                cumulative_length += font_size_count[size]
                if cumulative_length > total_text_length * 0.5:
                    small_font_threshold = size
                    break
            # 翻译文本
            updated_page_info = self.process_page_info(pages_info)

            new_page = output_doc.new_page(width=page.rect.width, height=page.rect.height)

            blocks = updated_page_info[0]['blocks']
            for block in blocks:
                if block["type"] == 0:  # 文本块
                    for line in block["lines"]:
                        for span in line["spans"]:
                            print("translated:", span["text"].strip(),
                                  (span["bbox"][0], span["bbox"][1] + span["size"]))
                            if span["size"] <= small_font_threshold:
                                fontname = "XinHuaSongTi-1"
                                fontfile = os.path.join(self.font_dir, f"{fontname}.ttf")
                            else:
                                fontname = "FZQiTi-S14S"
                                fontfile = os.path.join(self.font_dir, f"{fontname}.ttf")
                            new_page.insert_text(
                                point=(span["bbox"][0], span["bbox"][1] + span["size"]),
                                text=span["text"].strip(),
                                fontsize=int(span["size"]),
                                color=tuple(c / 255 for c in span["color"]),
                                render_mode=0,  # 使用默认渲染模式
                                encoding=0,
                                fontfile=fontfile,
                                fontname=fontname,
                            )
                elif block["type"] == 1:  # 图片块
                    try:
                        image = block["image"]
                        rect = fitz.Rect(block["bbox"])
                        # 插入图像
                        if inside_text:
                            pass
                        else:
                            new_page.insert_image(
                                rect,
                                stream=image,
                                xref=block.get("xref") if block.get("xref") else 0,
                                width=block["width"],
                                height=block["height"],
                            )
                    except Exception:
                        print(traceback.format_exc())
                else:
                    print(f"Unsupported block type: {block['type']}")
                    pass
        # 保存文档
        output_doc.save(output_pdf)
        output_doc.close()
        input_doc.close()