Warco-B commited on
Commit
5cbf2ba
1 Parent(s): 2157843

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +41 -31
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
- # extract text
73
- if pdf is not None:
74
- text = extract_text_from_pdf(pdf, start=start, stop=stop)
75
- chunks = split_text(text)
76
-
77
- translated_chunks = []
78
- for chunk in chunks:
79
- translated_chunk = translator.translate_chunk(chunk)
80
- translated_chunks.append(translated_chunk + " ")
81
-
82
- translated_text = ' '.join(translated_chunks)
83
- with open('translated.txt', 'w') as f:
84
- f.write(translated_text)
85
-
86
- return translated_text, "Translation Successful"
87
-
88
-
89
-
90
- iface = gr.Interface(title="Pdf Translator English -> Italian",
91
- fn=translate_pdf,
92
- inputs=[
93
- gr.inputs.Textbox(lines=1, label="OpenAI API key",
94
- placeholder="Enter your OpenAI API key here"),
95
- gr.inputs.File(type="binary", label="PDF file", ),
96
- gr.inputs.Number(label="Starting Page", ),
97
- gr.inputs.Number(label="Final Page")
98
- ],
99
- outputs=["text", "text"]
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()