Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -1,7 +1,7 @@
|
|
1 |
import gradio as gr
|
2 |
from io import BytesIO
|
3 |
import fitz
|
4 |
-
|
5 |
import openai
|
6 |
|
7 |
|
@@ -68,35 +68,45 @@ def split_text(text, chunk_size=100):
|
|
68 |
|
69 |
def translate_pdf(openai_key, pdf, start, stop):
|
70 |
translator = TranslationAgent(openai_key)
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
translated_chunks
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
101 |
|
102 |
iface.launch()
|
|
|
1 |
import gradio as gr
|
2 |
from io import BytesIO
|
3 |
import fitz
|
4 |
+
import tempfile
|
5 |
import openai
|
6 |
|
7 |
|
|
|
68 |
|
69 |
def translate_pdf(openai_key, pdf, start, stop):
|
70 |
translator = TranslationAgent(openai_key)
|
71 |
+
translated_text = ""
|
72 |
+
error_message = "Translation Successful"
|
73 |
+
|
74 |
+
try:
|
75 |
+
# extract text
|
76 |
+
if pdf is not None:
|
77 |
+
text = extract_text_from_pdf(pdf, start=start, stop=stop)
|
78 |
+
chunks = split_text(text)
|
79 |
+
|
80 |
+
translated_chunks = []
|
81 |
+
for chunk in chunks:
|
82 |
+
translated_chunk = translator.translate_chunk(chunk)
|
83 |
+
translated_chunks.append(translated_chunk + " ")
|
84 |
+
|
85 |
+
translated_text = ' '.join(translated_chunks)
|
86 |
+
except Exception as e:
|
87 |
+
error_message = f"Translation Failed: {e}"
|
88 |
+
|
89 |
+
# Create a temporary file with a specific prefix
|
90 |
+
temp = tempfile.NamedTemporaryFile(delete=False, prefix="translatedPDF_", suffix=".txt")
|
91 |
+
|
92 |
+
# Write to the temporary file
|
93 |
+
with open(temp.name, 'w', encoding='utf-8') as f:
|
94 |
+
f.write(translated_text)
|
95 |
+
|
96 |
+
return translated_text, error_message, temp.name
|
97 |
+
|
98 |
+
|
99 |
+
iface = gr.Interface(
|
100 |
+
fn=translate_pdf,
|
101 |
+
inputs=[
|
102 |
+
gr.Textbox(lines=1, label="OpenAI API key",
|
103 |
+
placeholder="Enter your OpenAI API key here"),
|
104 |
+
gr.File(type="binary", label="PDF file", ),
|
105 |
+
gr.Number(label="Starting Page", ),
|
106 |
+
gr.Number(label="Final Page")
|
107 |
+
],
|
108 |
+
outputs=["text", "text", gr.File(label="Translated Text File")],
|
109 |
+
title="Pdf Translator: English ==> Italian",
|
110 |
+
)
|
111 |
|
112 |
iface.launch()
|