Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

For local backend custom font path #307

Merged
merged 2 commits into from
Dec 20, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 21 additions & 12 deletions pdf2zh/high_level.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,8 @@ def translate_stream(
elif lang_out.lower() in noto_list: # noto
resfont = "noto"
# docker
ttf_path = "/app/GoNotoKurrent-Regular.ttf"
ttf_path = os.environ.get("NOTO_FONT_PATH", "/app/GoNotoKurrent-Regular.ttf")

if not os.path.exists(ttf_path):
ttf_path = os.path.join(tempfile.gettempdir(), "GoNotoKurrent-Regular.ttf")
if not os.path.exists(ttf_path):
Expand Down Expand Up @@ -330,13 +331,12 @@ def translate(
try:
r = requests.get(file, allow_redirects=True)
if r.status_code == 200:
if not os.path.exists("./pdf2zh_files"):
print("Making a temporary dir for downloading PDF files...")
os.mkdir(os.path.dirname("./pdf2zh_files"))
with open("./pdf2zh_files/tmp_download.pdf", "wb") as f:
with tempfile.NamedTemporaryFile(
suffix=".pdf", delete=False
) as tmp_file:
print(f"Writing the file: {file}...")
f.write(r.content)
file = "./pdf2zh_files/tmp_download.pdf"
tmp_file.write(r.content)
file = tmp_file.name
else:
r.raise_for_status()
except Exception as e:
Expand All @@ -348,13 +348,21 @@ def translate(
# If the commandline has specified converting to PDF/A format
# --compatible / -cp
if compatible:
file_pdfa = file.replace(".pdf", "-pdfa.pdf")
print(f"Converting {file} to PDF/A format...")
convert_to_pdfa(file, file_pdfa)
doc_raw = open(file_pdfa, "rb")
with tempfile.NamedTemporaryFile(
suffix="-pdfa.pdf", delete=False
) as tmp_pdfa:
print(f"Converting {file} to PDF/A format...")
convert_to_pdfa(file, tmp_pdfa.name)
doc_raw = open(tmp_pdfa.name, "rb")
os.unlink(tmp_pdfa.name)
else:
doc_raw = open(file, "rb")
s_raw = doc_raw.read()
doc_raw.close()

if file.startswith(tempfile.gettempdir()):
os.unlink(file)

s_mono, s_dual = translate_stream(
s_raw,
envs=kwarg.get("envs", {}),
Expand All @@ -367,7 +375,8 @@ def translate(
doc_dual = open(file_dual, "wb")
doc_mono.write(s_mono)
doc_dual.write(s_dual)
doc_mono.close()
doc_dual.close()
result_files.append((str(file_mono), str(file_dual)))

return result_files
return result_files
Loading