tomo2chin2 commited on
Commit
cf90d24
·
verified ·
1 Parent(s): 2bb7232

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +54 -24
app.py CHANGED
@@ -1,34 +1,64 @@
1
  import gradio as gr
2
  import base64
 
3
 
4
- def file_to_base64(file_path):
5
  """
6
- アップロードされたファイルのパスを受け取り、
7
- バイナリモードでファイルを読み込んで Base64 エンコードした文字列を返します。
8
  """
 
 
 
9
  try:
10
- with open(file_path, "rb") as f:
11
- data = f.read()
12
- encoded_str = base64.b64encode(data).decode("utf-8")
13
- return encoded_str
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  except Exception as e:
15
- return f"ファイルの変換中にエラーが発生しました: {e}"
16
-
17
- # Gradio インターフェースの定義
18
- demo = gr.Interface(
19
- fn=file_to_base64,
20
- inputs=gr.File(
21
- label="画像またはPDFファイルをアップロード",
22
- type="file",
23
- file_types=["jpg", "jpeg", "png", "pdf"]
24
- ),
25
- outputs=gr.Textbox(label="Base64 出力"),
26
- title="ファイルから Base64 変換アプリ",
27
- description="画像やPDFファイルをアップロードすると、その内容をBase64エンコードして表示します。"
28
  )
29
 
30
- # Hugging Face Spaces 用: Spaces は「app」という変数を探すため、これを定義します。
31
- app = demo
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
 
33
- if __name__ == "__main__":
34
- demo.launch()
 
1
  import gradio as gr
2
  import base64
3
+ import os # ファイルパスのデバッグ用に念のためインポート
4
 
5
+ def encode_to_base64(file_obj):
6
  """
7
+ gr.Fileから受け取ったファイルオブジェクトを読み込み、
8
+ Base64エンコードされた文字列を返す関数。
9
  """
10
+ if file_obj is None:
11
+ return "ファイルをアップロードしてください。"
12
+
13
  try:
14
+ # GradioのFileコンポーネントは一時ファイルオブジェクトを提供し、
15
+ # その .name 属性に一時ファイルのパスが含まれている
16
+ file_path = file_obj.name
17
+ print(f"処理中のファイル: {file_path}") # デバッグ用ログ
18
+
19
+ # ファイルをバイナリ読み込みモードで開く
20
+ with open(file_path, 'rb') as f:
21
+ # ファイルの内容全体をバイト列として読み込む
22
+ file_bytes = f.read()
23
+
24
+ # バイト列をBase64にエンコードする (結果もバイト列)
25
+ base64_bytes = base64.b64encode(file_bytes)
26
+
27
+ # Base64のバイト列をUTF-8文字列にデコードする
28
+ base64_string = base64_bytes.decode('utf-8')
29
+
30
+ return base64_string
31
+
32
  except Exception as e:
33
+ print(f"エラー発生: {e}") # デバッグ用ログ
34
+ return f"ファイルの処理中にエラーが発生しました: {e}"
35
+
36
+ # --- Gradioインターフェースの定義 ---
37
+
38
+ # 入力コンポーネント: ファイルアップロード
39
+ # file_typesで使用可能なファイル種別をユーザーに示す(画像全般とPDFを指定)
40
+ input_file = gr.File(
41
+ label="画像またはPDFファイルを入力",
42
+ file_types=['image', '.pdf'] # 'image'は一般的な画像形式をカバー, '.pdf'でPDFを指定
 
 
 
43
  )
44
 
45
+ # 出力コンポーネント: テキストボックス
46
+ # linesで高さを調整し、interactive=Trueでコピー可能にする
47
+ output_text = gr.Textbox(
48
+ label="Base64エンコード結果",
49
+ lines=10,
50
+ interactive=True # 結果をコピーできるようにする
51
+ )
52
+
53
+ # Gradioインターフェースを作成
54
+ iface = gr.Interface(
55
+ fn=encode_to_base64, # 実行する関数
56
+ inputs=input_file, # 入力コンポーネント
57
+ outputs=output_text, # 出力コンポーネント
58
+ title="ファイル ⇨ Base64 エンコーダー",
59
+ description="画像 (JPG, PNG, GIF等) または PDF ファイルをアップロードすると、その Base64 エンコードされた文字列が表示されます。",
60
+ allow_flagging='never' # Flagging機能が不要な場合は無効化
61
+ )
62
 
63
+ # アプリを起動
64
+ iface.launch()