分析下面的代码 下面是解析pdf文本然后翻译再次写入到pdf的功能 下面的代码实际是替换原有的文本 现在我需要增加 insidetext=True的功能 insidetext…
- User
分析下面的代码 下面是解析pdf文本然后翻译再次写入到pdf的功能 下面的代码实际是替换原有的文本 现在我需要增加 inside_text=True的功能 inside_text =True的时候 是在文本行的下面下入翻译的内容 不会覆盖原有的文本 也就是将pages_info内容写入到原有的位置 updated_page_info的内容写入原文本行的下面 字体大小为5号 颜色为红色 请你帮我完成代码
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=4.0): """ 将 spans 根据 y 坐标(bbox[1])、字体大小(size)和颜色(color)分组到同一行 :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 last_size = None last_color = None for span in spans_list_sorted: y = span['bbox'][1] size = span['size'] color = span['color'] if last_y is None or abs(y - last_y) > y_tolerance or size != last_size or color != last_color: # 开始新的一行 if current_line: lines.append(current_line) current_line = [span] last_y = y last_size = size last_color = color else: current_line.append(span) # 添加最后一行 if current_line: lines.append(current_line) return lines for i, page in enumerate(input_doc): # if i>13: # continue 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: # print("block",block["type"]) 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 "MCNAMEE/GETTY" in span["text"].strip(): print("WIN MCNAMEE/GETTY IMAGES") 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 = max(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) # print(f"origin : {len(spans_in_line)}", span["text"].strip(),(span["bbox"][0], span["bbox"][1]),(x0, y0)) if float(span["size"]) <7 and (span["bbox"][3]-span["bbox"][1]) / (span["bbox"][2]-span["bbox"][0])> 7: v = 90 else: v = 0 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"] , # 添加字体信息 "direction":v, }) 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") # if not span["text"].strip(): # continue direction = span["direction"] 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, rotate=direction, ) 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() - Assistant