hansech commited on
Commit
91624a2
·
verified ·
1 Parent(s): 63589a9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +64 -50
app.py CHANGED
@@ -1,87 +1,101 @@
1
  import gradio as gr
2
  import os
3
- import google.generativeai as genai
4
  import json
5
  import re
6
- import random # 匯入隨機數函式庫
7
 
8
- # --- 步驟一:設定與載入 Gemini 模型 ---
9
  GOOGLE_API_KEY = os.getenv('GOOGLE_API_KEY')
10
- gemini_model = None
11
- if GOOGLE_API_KEY:
12
- try:
13
- genai.configure(api_key=GOOGLE_API_KEY)
14
- gemini_model = genai.GenerativeModel('gemini-pro')
15
- print("INFO: Gemini model loaded successfully.")
16
- except Exception as e:
17
- print(f"ERROR: Failed to configure Gemini: {e}")
18
- else:
19
- print("WARNING: GOOGLE_API_KEY not found. Service will not function.")
20
 
21
- # --- 步驟二:定義最終的處理函數 ---
22
- def process_card_with_gemini(text):
23
  info = {
24
  'First Name': '', 'Last Name': '', 'E-mail': '', 'Phone': '', 'Mobile': '',
25
  'Address': '', 'Organization Name': '', 'Organization Title': '', 'Organization Department': '',
26
- 'Source Engine': 'Error - Gemini Disabled'
27
  }
28
 
29
- if not gemini_model or not text:
30
- if not gemini_model: info['First Name'] = 'Gemini Error'
31
  return info
32
 
33
- try:
34
- # *** 關鍵修正:加入快取破解符 (Cache Buster) ***
35
- cache_buster = random.randint(10000, 99999)
36
-
37
- print(f"INFO: Processing text with Gemini... (buster: {cache_buster})")
38
- prompt = f"""
39
- Analyze the following business card text and extract the information into a pure JSON object.
40
- - Split Chinese names into "First Name" and "Last Name". For "曾祐信", Last Name is "曾", First Name is "祐信".
41
- - Combine multi-line addresses into a single "Address" field.
42
- - Prioritize mobile numbers (starting with 09) for the "Mobile" field.
43
- - Other numbers go into the "Phone" field, including extensions.
44
- - If a field is not found, its value should be an empty string "".
45
- - CRITICAL: Respond ONLY with the JSON object, without any surrounding text, explanations, or markdown like ```json ... ```.
 
 
46
 
47
- TARGET FIELDS:
48
- "First Name", "Last Name", "E-mail", "Phone", "Mobile", "Address", "Organization Name", "Organization Title", "Organization Department"
49
 
50
- BUSINESS CARD TEXT:
51
- ---
52
- {text}
53
- ---
54
- (Technical instruction: Ignore this random number, it's for cache busting: {cache_buster})
55
- """
56
- response = gemini_model.generate_content(prompt)
57
- gemini_json_text = response.text.strip().replace("```json", "").replace("```", "").strip()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
 
59
- gemini_info = json.loads(gemini_json_text)
 
60
 
61
  for key in info.keys():
62
  if key not in gemini_info:
63
  gemini_info[key] = ''
64
 
65
- gemini_info['Source Engine'] = 'Gemini'
66
- print("INFO: Gemini processing successful.")
67
  return gemini_info
68
 
69
  except Exception as e:
70
- print(f"ERROR: An error occurred during Gemini processing: {e}")
71
- info['Source Engine'] = 'Gemini Error - Fallback'
 
72
  email_match = re.search(r'([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]{2,})', text)
73
  mobile_match = re.search(r'(09\d{2}[- ]?\d{3}[- ]?\d{3})', text)
74
  if email_match: info['E-mail'] = email_match.group(1).strip()
75
  if mobile_match: info['Mobile'] = mobile_match.group(1).strip()
76
  return info
77
 
78
- # --- 步驟三:建立並啟動 Gradio 服務 (回歸最簡潔的 Interface 模式) ---
79
  interface = gr.Interface(
80
- fn=process_card_with_gemini,
81
  inputs=gr.Textbox(lines=15, label="請輸入名片內容"),
82
  outputs=gr.JSON(label="辨識結果"),
83
- title="中文名片智慧辨識 API (Gemini-First, v2)",
84
- description="使用 Google Gemini 進行高精度名片辨識。",
85
  api_name="predict"
86
  )
87
 
 
1
  import gradio as gr
2
  import os
 
3
  import json
4
  import re
5
+ import requests # 使用 requests 函式庫
6
 
7
+ # --- 步驟一:設定 ---
8
  GOOGLE_API_KEY = os.getenv('GOOGLE_API_KEY')
9
+ # 我們將直接在函數中使用 API Key,不再需要載入 Gemini 模型
 
 
 
 
 
 
 
 
 
10
 
11
+ # --- 步驟二:定義最終的處理函數 (使用 requests) ---
12
+ def process_card_with_direct_api(text):
13
  info = {
14
  'First Name': '', 'Last Name': '', 'E-mail': '', 'Phone': '', 'Mobile': '',
15
  'Address': '', 'Organization Name': '', 'Organization Title': '', 'Organization Department': '',
16
+ 'Source Engine': 'Error - API Key Missing'
17
  }
18
 
19
+ if not GOOGLE_API_KEY or not text:
20
+ if not GOOGLE_API_KEY: info['First Name'] = 'API Key Error'
21
  return info
22
 
23
+ # --- 使用 requests 直接呼叫 Google AI v1 穩定版 API ---
24
+ api_url = f"https://generativelanguage.googleapis.com/v1/models/gemini-pro:generateContent?key={GOOGLE_API_KEY}"
25
+
26
+ headers = {
27
+ "Content-Type": "application/json"
28
+ }
29
+
30
+ prompt = f"""
31
+ Analyze the following business card text and extract the information into a pure JSON object.
32
+ - Split Chinese names into "First Name" and "Last Name". For "曾祐信", Last Name is "曾", First Name is "祐信".
33
+ - Combine multi-line addresses into a single "Address" field.
34
+ - Prioritize mobile numbers (starting with 09) for the "Mobile" field.
35
+ - Other numbers go into the "Phone" field, including extensions.
36
+ - If a field is not found, its value should be an empty string "".
37
+ - CRITICAL: Respond ONLY with the JSON object, without any surrounding text, explanations, or markdown like ```json ... ```.
38
 
39
+ TARGET FIELDS:
40
+ "First Name", "Last Name", "E-mail", "Phone", "Mobile", "Address", "Organization Name", "Organization Title", "Organization Department"
41
 
42
+ BUSINESS CARD TEXT:
43
+ ---
44
+ {text}
45
+ ---
46
+ """
47
+
48
+ body = {
49
+ "contents": [
50
+ {
51
+ "parts": [
52
+ {
53
+ "text": prompt
54
+ }
55
+ ]
56
+ }
57
+ ]
58
+ }
59
+
60
+ try:
61
+ print("INFO: Calling Google AI v1 API directly...")
62
+ response = requests.post(api_url, headers=headers, json=body, timeout=60)
63
+ response.raise_for_status() # 如果 API 回傳錯誤 (如 4xx, 5xx), 會在此拋出異常
64
+
65
+ response_json = response.json()
66
+
67
+ # 提取 Gemini 回傳的 JSON 文字
68
+ gemini_output_text = response_json['candidates'][0]['content']['parts'][0]['text']
69
+ gemini_output_text = gemini_output_text.strip().replace("```json", "").replace("```", "").strip()
70
 
71
+ # 解析 JSON
72
+ gemini_info = json.loads(gemini_output_text)
73
 
74
  for key in info.keys():
75
  if key not in gemini_info:
76
  gemini_info[key] = ''
77
 
78
+ gemini_info['Source Engine'] = 'Gemini (v1 API)'
79
+ print("INFO: Direct API call successful.")
80
  return gemini_info
81
 
82
  except Exception as e:
83
+ print(f"ERROR: An error occurred during direct API call: {e}")
84
+ # 如果 API 呼叫失敗,至少回傳 RegEx 抓到的基本聯絡資訊
85
+ info['Source Engine'] = 'Direct API Error - Fallback'
86
  email_match = re.search(r'([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]{2,})', text)
87
  mobile_match = re.search(r'(09\d{2}[- ]?\d{3}[- ]?\d{3})', text)
88
  if email_match: info['E-mail'] = email_match.group(1).strip()
89
  if mobile_match: info['Mobile'] = mobile_match.group(1).strip()
90
  return info
91
 
92
+ # --- 步驟三:建立並啟動 Gradio 服務 ---
93
  interface = gr.Interface(
94
+ fn=process_card_with_direct_api,
95
  inputs=gr.Textbox(lines=15, label="請輸入名片內容"),
96
  outputs=gr.JSON(label="辨識結果"),
97
+ title="中文名片智慧辨識 API (Direct API v3)",
98
+ description="直接呼叫 Google v1 API,以獲取最高穩定性。",
99
  api_name="predict"
100
  )
101