蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行三种文档输入和 JSON 输出合同

PYTHONWindows、Python 3.12。各实验所需工具和版本见下载包 README。summarize.py
summarize.py150 行
"""Create a grounded, extractive recap of a local text, PDF or Word file."""
import argparse
from collections import Counter
from importlib import import_module
import io
import json
from pathlib import Path
import re
import sys
from zipfile import BadZipFile

FORMATS={".txt":"text",".pdf":"pdf",".docx":"docx"}
DEPENDENCIES={"pdf":("pypdfium2","pypdfium2"),"docx":("docx","python-docx")}
MAX_BYTES=10*1024*1024
STOP={"the","for","are","was","with","and","from","this","that","these"}


class ContractError(Exception):
    def __init__(self,status,code,message,action,exit_code):
        super().__init__(message)
        self.status,self.code,self.action,self.exit_code=status,code,action,exit_code

    def payload(self):
        return dict(status=self.status,error={"code":self.code,"message":str(self),"action":self.action})


def extract(raw,kind):
    if kind=="text":
        return None,raw.decode("utf-8-sig")
    module,package=DEPENDENCIES[kind]
    try:
        reader=import_module(module)
    except ModuleNotFoundError as error:
        if error.name!=module:
            raise
        raise ContractError("process_error","MISSING_DEPENDENCY",f"reader {package} is unavailable",
                            "run with the declared dependency in a separate environment",4) from error
    if kind=="docx":
        try:
            doc=reader.Document(io.BytesIO(raw))
        except (ValueError,BadZipFile,KeyError) as error:
            raise ContractError("process_error","DAMAGED_DOCX","unable to read the Word package",
                                "open and repair or re-export the document",4) from error
        blocks=[p.text for p in doc.paragraphs]
        for table in doc.tables:
            blocks.extend(" | ".join(cell.text for cell in row.cells) for row in table.rows)
        return None,"\n".join(blocks)
    try:
        with reader.PdfDocument(raw) as pdf:
            blocks=[]
            for index in range(len(pdf)):
                page=pdf[index]
                try:
                    text=page.get_textpage()
                    try:
                        blocks.append(text.get_text_bounded())
                    finally:
                        text.close()
                finally:
                    page.close()
            return len(pdf),"\n".join(blocks)
    except reader.PdfiumError as error:
        raise ContractError("process_error","DAMAGED_PDF","unable to open the PDF reader",
                            "use a valid unlocked PDF or re-export it",4) from error


def recap(text,length,focus):
    # Keep the original sentence text and its ordering when possible.
    chunks=[line.strip() for line in re.split(r"(?<=[.!?。!?])\s+|[\r\n]+",text) if line.strip()]
    if focus:
        chunks=sorted(chunks,key=lambda item:focus.casefold() not in item.casefold())
    take={"short":3,"medium":5,"long":9}[length]
    selected=chunks[:take]
    if length=="long":
        return "\n\n".join(" ".join(selected[i:i+3]) for i in range(0,len(selected),3))
    return " ".join(selected)


def summarize(path,length,focus,progress,limit):
    if path is None:
        raise ContractError("input_error","MISSING_INPUT","no input file was supplied","choose a local document",2)
    kind=FORMATS.get(path.suffix.casefold())
    if kind is None:
        raise ContractError("input_error","FORMAT","expected .txt, .pdf or .docx","choose a supported file format",2)
    with path.open("rb") as stream:
        raw=stream.read(limit+1)
    if not raw:
        raise ContractError("input_error","EMPTY","input file is empty","choose a file containing text",2)
    if len(raw)>limit:
        raise ContractError("input_error","SIZE","input exceeds the byte limit","split the document before retry",2)
    if progress:
        print(f"read {len(raw)} bytes",file=sys.stderr,flush=True)
    page_count,text=extract(raw,kind)
    if not text.strip():
        code="NO_TEXT_LAYER" if kind=="pdf" else "NO_TEXT"
        action="use OCR for an image-only PDF" if kind=="pdf" else "supply a file with nonempty text"
        raise ContractError("result_error",code,"no text was returned by the reader",action,5)
    words=re.findall(r"\b[\w-]+\b",text)
    counts=Counter(w.casefold() for w in words if len(w)>2 and w.casefold() not in STOP)
    result=dict(title=next(line.strip() for line in text.splitlines() if line.strip()),
                pages=page_count,word_count_estimate=len(words),length=length,method="extractive_local",
                summary=recap(text,length,focus),keywords=[word for word,_ in counts.most_common(8)])
    if not result["summary"]:
        raise ContractError("result_error","EMPTY_SUMMARY","no extract could be produced","review the source text",5)
    if progress:
        print("summary ready",file=sys.stderr,flush=True)
    return result


def main(argv=None):
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument("path",type=Path,nargs="?")
    parser.add_argument("--length",choices=["short","medium","long"],default="medium")
    parser.add_argument("--focus",default="")
    parser.add_argument("--progress",action="store_true")
    parser.add_argument("--max-bytes",type=int,default=MAX_BYTES)
    parser.add_argument("--output",type=Path)
    args=parser.parse_args(argv)
    try:
        if not 0<args.max_bytes<=MAX_BYTES:
            raise ContractError("input_error","INVALID_LIMIT","byte limit must be within the supported range",
                                "choose a positive limit up to 10 MiB",2)
        data=summarize(args.path,args.length,args.focus,args.progress,args.max_bytes)
        result=dict(status="success",data=data)
        if args.output:
            with args.output.open("x",encoding="utf8") as target:
                json.dump(result,target,ensure_ascii=False)
                target.write("\n")
    except ContractError as error:
        result=error.payload()
        code=error.exit_code
    except FileNotFoundError:
        result=ContractError("input_error","NOT_FOUND","input or output directory not found","check the specified location",2).payload()
        code=2
    except UnicodeDecodeError:
        result=ContractError("process_error","ENCODING","input could not be decoded", "provide UTF-8 text or a new export",4).payload()
        code=4
    except (OSError,ModuleNotFoundError):
        result=ContractError("process_error","READER_OR_IO","reader or file operation failed",
                             "check dependencies, use an authorized location and a new output name",4).payload()
        code=4
    else:
        code=0
    print(json.dumps(result,ensure_ascii=False))
    return code


if __name__=="__main__":
    raise SystemExit(main())
本例需在 Windows、Python 3.12。各实验所需工具和版本见下载包 README。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows、Python 3.12。各实验所需工具和版本见下载包 README。

入口文件:projects/skills-docs/summarize.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 summarize.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows、Python 3.12。各实验所需工具和版本见下载包 README。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Skills(技能)

课程关联工程包(登记关联39章) · 含当前章节或实例 · mbskycom202612a331.zip

下载课程关联工程包:Skills(技能)

课程关联工程包(登记关联2章) · 含当前章节或实例 · mbskycom202612a339.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习