分析下面的代码 主要是解析pdf 然后将pdf的文本内容翻译 然后 将翻译的结果再次写入到pdf中 有一个问题是 下面的代码 会产生翻译后的文本写入后 部分位置出现文字覆盖…
- User
分析下面的代码 主要是解析pdf 然后将pdf的文本内容翻译 然后 将翻译的结果再次写入到pdf中 有一个问题是 下面的代码 会产生翻译后的文本写入后 部分位置出现文字覆盖 重叠的情况 分析原因是 for line in lines:遍历的时候 lines每个元素本应该是不同的行 实际上不是 因此需要写一个函数来对lines进行处理 确认处于同一行的标准应该是span["bbox"][1]的值是相同的 不能直接遍历出所有的spans 然后排序 需要遍历lines 在遍历span 一层层的进行 self.process_page_info是翻译文本的函数 请你帮我修改代码
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() for i, page in enumerate(input_doc): # if i!=0: # 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 text_ ="" for block in page_blocks: if block["type"] == 0: lines_info = [] i = 0 lines = block["lines"] for line in lines: spans_info = [] for span in line["spans"]: text = span["text"] # print(f"text {len(line['spans'])}:",text,(span["bbox"][0], span["bbox"][1]+span["size"])) if i == 0 and len(text.strip())==1: text_ = text continue if span["font"] not in font_list: font_list.append(span["font"]) # 统计字体大小 font_size_count[span["size"]] += len(text) total_text_length += len(text) spans_info.append({ "text": text_+text, "size": span["size"], "color": fitz.sRGB_to_rgb(span["color"]), "bbox": span["bbox"], 'ascender': span['ascender'], 'descender': span['descender'], 'origin': span['origin'], "font": span["font"] # 添加字体信息 }) text_ = "" i+=1 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"]), # fontname=span.get("font",""), # 使用原始字体 tuple(c/255 for c in span["color"]) color=tuple(c/255 for c in span["color"]), # color= span["color"], # ascender = span["ascender"], # descender=span["descender"], # flags=span["flags"], # origin=span["origin"], render_mode=0 , # 使用默认渲染模式, encoding=0, fontfile=fontfile, fontname=fontname, ) elif block["type"] == 1: # 图片块 try: image = block["image"] rect = fitz.Rect(block["bbox"]) # 应用变换 # if "transform" in block.keys(): # transform = block["transform"] # matrix = fitz.Matrix(transform[0], transform[1], transform[2], transform[3], transform[4], transform[5]) # rect = rect.transform(matrix) # new_page.insert_image(rect, stream=image) # 插入图像 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"], # colorspace=block["colorspace"], # bpc=block["bpc"], ) except Exception: print(traceback.format_exc()) else: print(f"Unsupported block type: {block['type']}") pass # 保存文档 else: output_doc.save(output_pdf) output_doc.close() input_doc.close() - Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.