tomo2chin2 commited on
Commit
5bb44a9
·
verified ·
1 Parent(s): 58ac360

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +66 -19
app.py CHANGED
@@ -6,6 +6,11 @@ import google.generativeai as genai
6
  import tempfile
7
  import base64
8
  from concurrent.futures import ThreadPoolExecutor
 
 
 
 
 
9
 
10
  # Gemini APIの設定 (環境変数から取得)
11
  GOOGLE_API_KEY = os.environ.get("GOOGLE_API_KEY")
@@ -13,12 +18,6 @@ if not GOOGLE_API_KEY:
13
  raise ValueError("環境変数 'GOOGLE_API_KEY' が設定されていません。")
14
  genai.configure(api_key=GOOGLE_API_KEY)
15
 
16
- import logging
17
-
18
- # ロギング設定
19
- logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
20
-
21
-
22
 
23
  def split_pdf(pdf_path, output_dir, pages_per_chunk=5):
24
  """PDFを指定ページ数ごとに分割する関数"""
@@ -60,7 +59,7 @@ def ocr_pdf_with_gemini(pdf_path):
60
  pdf_base64 = encode_pdf_to_base64(pdf_path)
61
 
62
  # Geminiモデルの設定
63
- model = genai.GenerativeModel('gemini-1.5-pro') # モデル名を変更
64
 
65
  # プロンプトの設定
66
  prompt = """
@@ -83,37 +82,48 @@ def ocr_pdf_with_gemini(pdf_path):
83
  # 結果を返す
84
  return response.text
85
  except Exception as e:
86
- print(f"Error during Gemini API call: {e}") # エラーを出力
87
- return f"エラーが発生しました: {e}" # ユーザー向けのエラーメッセージ
88
 
89
 
90
- def process_pdf(pdf_file):
91
  """PDFファイルを処理するメイン関数"""
92
- logging.info(f"Received file: {pdf_file.name if hasattr(pdf_file, 'name') else pdf_file}") # ファイル名/オブジェクトのログ
93
 
94
  # 一時ディレクトリを作成
95
  with tempfile.TemporaryDirectory() as temp_dir:
96
- # Gradioから渡されるのはNamedStringオブジェクトなので、.nameでファイルパスを取得
97
  temp_pdf_path = pdf_file.name
98
-
99
-
100
  logging.info(f"Temporary PDF path: {temp_pdf_path}")
101
 
102
- # PDFを分割 (split_pdf に渡すパスは変更なし)
103
  split_pdf_paths = split_pdf(temp_pdf_path, temp_dir)
104
  logging.info(f"Split PDF paths: {split_pdf_paths}")
 
105
 
106
  # 並列処理でOCR変換
107
  markdown_results = []
108
  with ThreadPoolExecutor() as executor:
109
- markdown_results = list(executor.map(ocr_pdf_with_gemini, split_pdf_paths))
110
- logging.info(f"Markdown results length: {len(markdown_results)}")
 
 
 
 
 
 
 
 
111
 
 
 
112
  # 結果を結合
113
  combined_markdown = "\n\n".join(markdown_results)
 
 
114
 
115
  return combined_markdown
116
 
 
117
  # Gradioインターフェースの作成
118
  def create_interface():
119
  with gr.Blocks() as demo:
@@ -124,10 +134,22 @@ def create_interface():
124
  pdf_input = gr.File(label="PDFファイルをアップロード", file_types=[".pdf"])
125
 
126
  with gr.Row():
127
- convert_btn = gr.Button("変換開始")
 
 
 
128
 
129
  with gr.Row():
130
- markdown_output = gr.Markdown(label="変換結果")
 
 
 
 
 
 
 
 
 
131
 
132
  convert_btn.click(
133
  fn=process_pdf,
@@ -135,6 +157,31 @@ def create_interface():
135
  outputs=markdown_output
136
  )
137
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
138
  return demo
139
 
140
 
 
6
  import tempfile
7
  import base64
8
  from concurrent.futures import ThreadPoolExecutor
9
+ import logging
10
+ import time # インポート追加
11
+
12
+ # ロギング設定
13
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
14
 
15
  # Gemini APIの設定 (環境変数から取得)
16
  GOOGLE_API_KEY = os.environ.get("GOOGLE_API_KEY")
 
18
  raise ValueError("環境変数 'GOOGLE_API_KEY' が設定されていません。")
19
  genai.configure(api_key=GOOGLE_API_KEY)
20
 
 
 
 
 
 
 
21
 
22
  def split_pdf(pdf_path, output_dir, pages_per_chunk=5):
23
  """PDFを指定ページ数ごとに分割する関数"""
 
59
  pdf_base64 = encode_pdf_to_base64(pdf_path)
60
 
61
  # Geminiモデルの設定
62
+ model = genai.GenerativeModel('gemini-1.5-pro') # または利用可能な他のモデル
63
 
64
  # プロンプトの設定
65
  prompt = """
 
82
  # 結果を返す
83
  return response.text
84
  except Exception as e:
85
+ logging.error(f"Error during Gemini API call: {e}")
86
+ return f"エラーが発生しました: {e}"
87
 
88
 
89
+ def process_pdf(pdf_file, progress=gr.Progress()):
90
  """PDFファイルを処理するメイン関数"""
91
+ logging.info(f"Received file: {pdf_file.name if hasattr(pdf_file, 'name') else pdf_file}")
92
 
93
  # 一時ディレクトリを作成
94
  with tempfile.TemporaryDirectory() as temp_dir:
 
95
  temp_pdf_path = pdf_file.name
 
 
96
  logging.info(f"Temporary PDF path: {temp_pdf_path}")
97
 
98
+ # PDFを分割
99
  split_pdf_paths = split_pdf(temp_pdf_path, temp_dir)
100
  logging.info(f"Split PDF paths: {split_pdf_paths}")
101
+ progress(0.2, desc="PDFを分割中...") # 進捗更新
102
 
103
  # 並列処理でOCR変換
104
  markdown_results = []
105
  with ThreadPoolExecutor() as executor:
106
+ # futureオブジェクトのリストを作成し、進捗を追跡
107
+ futures = [executor.submit(ocr_pdf_with_gemini, path) for path in split_pdf_paths]
108
+ for i, future in enumerate(futures):
109
+ try:
110
+ result = future.result()
111
+ markdown_results.append(result)
112
+ progress(0.2 + 0.6 * (i + 1) / len(futures), desc="OCR処理中...") # 進捗更新
113
+ except Exception as e:
114
+ logging.error(f"Error processing split PDF: {e}")
115
+ markdown_results.append(f"分割PDFの処理中にエラーが発生しました: {e}")
116
 
117
+ logging.info(f"Markdown results length: {len(markdown_results)}")
118
+ progress(0.8, desc="結果を結合中...")# 進捗更新
119
  # 結果を結合
120
  combined_markdown = "\n\n".join(markdown_results)
121
+ progress(1.0, desc="完了") # 進捗更新
122
+ time.sleep(0.5) #完了表示のため少し待つ
123
 
124
  return combined_markdown
125
 
126
+
127
  # Gradioインターフェースの作成
128
  def create_interface():
129
  with gr.Blocks() as demo:
 
134
  pdf_input = gr.File(label="PDFファイルをアップロード", file_types=[".pdf"])
135
 
136
  with gr.Row():
137
+ convert_btn = gr.Button("変換開始", variant="primary", elem_id="convert-button") # variantとelem_idを追加
138
+
139
+ with gr.Row():
140
+ markdown_output = gr.Textbox(label="変換結果", lines=10, max_lines=20) # MarkdownからTextboxに変更、行数を指定
141
 
142
  with gr.Row():
143
+ copy_btn = gr.Button("クリップボードにコピー")
144
+ download_btn = gr.Button("ダウンロード")
145
+
146
+ # スタイル設定 (CSS)
147
+ demo.load(None, None, None, _js="""
148
+ () => {
149
+ document.getElementById('convert-button').style.backgroundColor = 'orange';
150
+ }
151
+ """)
152
+
153
 
154
  convert_btn.click(
155
  fn=process_pdf,
 
157
  outputs=markdown_output
158
  )
159
 
160
+ # クリップボードにコピー
161
+ copy_btn.click(
162
+ None,
163
+ markdown_output,
164
+ [],
165
+ js=f"(x) => {{ navigator.clipboard.writeText(x); }}",
166
+ )
167
+
168
+ # ダウンロード
169
+ download_btn.click(
170
+ None,
171
+ markdown_output,
172
+ [],
173
+ js=f"""(x) =>{{
174
+ const blob = new Blob([x], {{type: 'text/markdown;charset=utf-8'}});
175
+ const url = URL.createObjectURL(blob);
176
+ const a = document.createElement('a');
177
+ a.href = url;
178
+ a.download = 'converted.md';
179
+ document.body.appendChild(a);
180
+ a.click();
181
+ document.body.removeChild(a);
182
+ URL.revokeObjectURL(url);
183
+ }}"""
184
+ )
185
  return demo
186
 
187