Spaces:
Running
Running
Update app.py
Browse files51 unmodified lines525354555657586 unmodified lines65666768697071727374757623 unmodified lines10010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613727 unmodified lines1651661671681691701713 unmodified lines17517617717817918018118218318418518618718822 unmodified lines2112122132142152162172182192202212222232246 unmodified lines23123223323423523623723823924024124224324424524624724824913 unmodified lines26326426526626726826923 unmodified lines2932942952962972982992 unmodified lines30230330430530630730811 unmodified lines3203213223233243253267 unmodified lines3343353363373383393403413425 unmodified lines3483493503513523533543553563573588 unmodified lines36736836937037137237337437510 unmodified lines38638738838939039139239339451 unmodified linesdef send_pdf_to_parse(file_path, server_ip, port, route="/upload", api_key=None):url = f"http://{server_ip}:{port}{route}"headers = {}if api_key:headers["Authorization"] = f"Bearer {api_key}"6 unmodified linesasync def send_pdf_async_aiohttp(file_path, server_ip, port, route="/upload", api_key=None):"""使用aiohttp异步发送PDF"""url = f"http://{server_ip}:{port}{route}"headers = {}if api_key:headers["Authorization"] = f"Bearer {api_key}"try:async with aiohttp.ClientSession() as session:23 unmodified linesPORT = os.environ.get("PORT")client = AsyncOpenAI(api_key=openai_api_key,base_url=openai_api_base,)async def request(messages):chat_completion_from_base64 = await client.chat.completions.create(messages=messages,model="Qwen2_5VL",max_completion_tokens=4096,stream=True,temperature=0.0,top_p=0.95)page = ""async for chunk in chat_completion_from_base64:if chunk.choices[0].delta.content:content = chunk.choices[0].delta.contentchoice = chunk.choices[0]if choice.finish_reason is not None:print(f"end reason = {choice.finish_reason}")breakpage += contentyield contentdef images_to_pdf(img_paths, pdf_path):27 unmodified linesreturn base64.b64encode(image_file.read()).decode("utf-8")def build_message(image_path, prompt):content = [{"type": "image_url",3 unmodified lines},{"type": "text", 'text': prompt}]messages = [{"role": "system", "content": "You are a helpful assistant."},{'role': 'user', 'content': content}]return messages22 unmodified linesfor idx, page in enumerate(pages, start=1):img_path = tmpdir / f"page_{idx}.png"page.save(img_path, "PNG")messages = build_message(img_path, prompt)queries.append(messages)else:messages = build_message(doc_path, prompt)queries.append(messages)all_pages = []all_pages_raw = []for query in queries:6 unmodified linesprint(all_pages)yield "\n---\n".join(all_pages), "\n\n".join(all_pages_raw)def compress_directory_to_zip(directory_path, output_zip_path):try:with zipfile.ZipFile(output_zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:for root, dirs, files in os.walk(directory_path):for file in files:file_path = os.path.join(root, file)arcname = os.path.relpath(file_path, directory_path)zipf.write(file_path, arcname)return 0except Exception as e:13 unmodified linesreturn promptdef to_file(image_path):if image_path.endswith("Academic_Papers.png"):image_path = image_path.replace("Academic_Papers.png", "Academic_Papers.pdf")23 unmodified linesimages_to_pdf(file_path, tmp_file_path)else:tmp_file_path = file_pathasyncio.create_task(send_pdf_async_aiohttp(tmp_file_path, IP, PORT))return str(tmp_file_path)2 unmodified lineswith gr.Blocks() as demo:with gr.Row():with gr.Column(variant='panel', scale=5):file = gr.File(label='Please upload a PDF or image', file_types=['.pdf', '.png', '.jpeg', '.jpg'], type="filepath")prompts = gr.Dropdown(choices=preset_prompts,11 unmodified linespdf_show = PDF(label='Preview', interactive=False, visible=True, height=800)example_root = os.path.join(os.path.dirname(__file__), 'examples')images = [os.path.join(example_root, f)7 unmodified linesfile_path = [os.path.join(example_root, f)for f in ["Financial_Reports.png", "Books.png", "Magazines.png", "Academic_Papers.png"]]with gr.Row():for i, label in enumerate(["Financial Reports(IMG)", "Books(IMG)", "Magazines(IMG)", "Academic Papers(PDF)"]):with gr.Column(scale=1, min_width=120):5 unmodified linesshow_download_button=False)gr.Button(label).click(fn=to_file, inputs=gr.State(file_path[i]), outputs=file)download_btn = gr.Button("⬇️ Generate download link", size="sm")output_file = gr.File(label='Parse result', interactive=False, elem_id="down-file-box",visible=False)gr.HTML("""<style>#down-file-box {8 unmodified linesline_breaks=True)with gr.Tab('Markdown text'):md_text = gr.TextArea(lines=45, show_copy_button=True)file.change(fn=process_file, inputs=file, outputs=pdf_show)10 unmodified linesinputs=[file, prompts],outputs=[md, md_text])clear_bu.add([file, md, pdf_show, md_text])download_btn.click(fn=download_markdown_file,inputs=md_text,51 unmodified lines525354555657586 unmodified lines65666768697071727374757623 unmodified lines10010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914027 unmodified lines1681691701711721731743 unmodified lines17817918018118218318418518618718818919019122 unmodified lines2142152162172182192202212222232242252262276 unmodified lines23423523623723823924024124224324424524624724824925025125213 unmodified lines26626726826927027127223 unmodified lines2962972982993003013022 unmodified lines30530630730830931031111 unmodified lines3233243253263273283297 unmodified lines3373383393403413423433443455 unmodified lines3513523533543553563573583593603618 unmodified lines37037137237337437537637737810 unmodified lines38939039139239339439539639751 unmodified linesdef send_pdf_to_parse(file_path, server_ip, port, route="/upload", api_key=None):url = f"{openai_api_base}{route}"headers = {}if api_key:headers["Authorization"] = f"Bearer {api_key}"6 unmodified linesasync def send_pdf_async_aiohttp(file_path, server_ip, route="/upload", Authorization=None):"""使用aiohttp异步发送PDF"""url = f"http://{server_ip}:{port}{route}"headers = {}if Authorization:headers["Authorization"] = f"Bearer {Authorization}"try:async with aiohttp.ClientSession() as session:23 unmodified linesPORT = os.environ.get("PORT")Authorization = os.environ.get("Authorization")client = AsyncOpenAI(api_key=openai_api_key,base_url=openai_api_base + "/v1",)async def request(messages):chat_completion_from_base64 = await client.chat.completions.create(messages=messages,extra_headers={"Authorization": f"Bearer {Authorization}"},model="Qwen2_5VL",max_completion_tokens=4096,stream=True,temperature=0.0,top_p=0.95)page = ""async for chunk in chat_completion_from_base64:if chunk.choices[0].delta.content:content = chunk.choices[0].delta.contentchoice = chunk.choices[0]if choice.finish_reason is not None:print(f"end reason = {choice.finish_reason}")breakpage += contentyield contentdef images_to_pdf(img_paths, pdf_path):27 unmodified linesreturn base64.b64encode(image_file.read()).decode("utf-8")def build_message(image_path, prompt):content = [{"type": "image_url",3 unmodified lines},{"type": "text", 'text': prompt}]messages = [{"role": "system", "content": "You are a helpful assistant."},{'role': 'user', 'content': content}]return messages22 unmodified linesfor idx, page in enumerate(pages, start=1):img_path = tmpdir / f"page_{idx}.png"page.save(img_path, "PNG")messages = build_message(img_path, prompt)queries.append(messages)else:messages = build_message(doc_path, prompt)queries.append(messages)all_pages = []all_pages_raw = []for query in queries:6 unmodified linesprint(all_pages)yield "\n---\n".join(all_pages), "\n\n".join(all_pages_raw)def compress_directory_to_zip(directory_path, output_zip_path):try:with zipfile.ZipFile(output_zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:for root, dirs, files in os.walk(directory_path):for file in files:file_path = os.path.join(root, file)arcname = os.path.relpath(file_path, directory_path)zipf.write(file_path, arcname)return 0except Exception as e:13 unmodified linesreturn promptdef to_file(image_path):if image_path.endswith("Academic_Papers.png"):image_path = image_path.replace("Academic_Papers.png", "Academic_Papers.pdf")23 unmodified linesimages_to_pdf(file_path, tmp_file_path)else:tmp_file_path = file_pathasyncio.create_task(send_pdf_async_aiohttp(tmp_file_path, server_ip=openai_api_base, Authorization=Authorization))return str(tmp_file_path)2 unmodified lineswith gr.Blocks() as demo:with gr.Row():with gr.Column(variant='panel', scale=5):file = gr.File(label='Please upload a PDF or image', file_types=['.pdf', '.png', '.jpeg', '.jpg'], type="filepath")prompts = gr.Dropdown(choices=preset_prompts,11 unmodified linespdf_show = PDF(label='Preview', interactive=False, visible=True, height=800)example_root = os.path.join(os.path.dirname(__file__), 'examples')images = [os.path.join(example_root, f)7 unmodified linesfile_path = [os.path.join(example_root, f)for f in ["Financial_Reports.png", "Books.png", "Magazines.png", "Academic_Papers.png"]]with gr.Row():for i, label in enumerate(["Financial Reports(IMG)", "Books(IMG)", "Magazines(IMG)", "Academic Papers(PDF)"]):with gr.Column(scale=1, min_width=120):5 unmodified linesshow_download_button=False)gr.Button(label).click(fn=to_file, inputs=gr.State(file_path[i]), outputs=file)download_btn = gr.Button("⬇️ Generate download link", size="sm")output_file = gr.File(label='Parse result', interactive=False, elem_id="down-file-box",visible=False)gr.HTML("""<style>#down-file-box {8 unmodified linesline_breaks=True)with gr.Tab('Markdown text'):md_text = gr.TextArea(lines=45, show_copy_button=True)file.change(fn=process_file, inputs=file, outputs=pdf_show)10 unmodified linesinputs=[file, prompts],outputs=[md, md_text])clear_bu.add([file, md, pdf_show, md_text])download_btn.click(fn=download_markdown_file,inputs=md_text,
app.py+40-37