jerrychen428 commited on
Commit
ec593e6
·
verified ·
1 Parent(s): 11f0666

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +182 -183
app.py CHANGED
@@ -1,209 +1,208 @@
1
  import gradio as gr
2
- import os
3
  from twilio.rest import Client
4
- import requests
5
- import json
 
6
 
7
- class APIManager:
8
- def __init__(self):
9
- self.twilio_client = None
10
- self.groq_api_key = None
11
- self.twilio_from_number = None
12
-
13
- def update_credentials(self, twilio_sid, twilio_token, twilio_from, groq_key):
14
- """更新 API 憑證"""
15
- try:
16
- # 驗證 Twilio 憑證
17
- if twilio_sid and twilio_token:
18
- test_client = Client(twilio_sid, twilio_token)
19
- # 簡單測試連接
20
- test_client.api.accounts(twilio_sid).fetch()
21
- self.twilio_client = test_client
22
- self.twilio_from_number = twilio_from
23
-
24
- # 更新 GROQ API Key
25
- if groq_key:
26
- self.groq_api_key = groq_key
27
-
28
- return "✅ API 憑證更新成功!", gr.update(visible=True)
29
- except Exception as e:
30
- return f"❌ 憑證驗證失敗: {str(e)}", gr.update(visible=False)
31
-
32
- # 創建 API 管理器實例
33
- api_manager = APIManager()
34
 
35
- def send_sms(to_number, message):
36
- """發送 SMS 訊息"""
37
- if not api_manager.twilio_client:
38
- return "❌ 請先設定 Twilio 憑證"
 
 
 
 
 
 
 
39
 
40
- try:
41
- message_obj = api_manager.twilio_client.messages.create(
42
- body=message,
43
- from_=api_manager.twilio_from_number,
44
- to=to_number
45
- )
46
- return f"✅ SMS 發送成功!訊息 SID: {message_obj.sid}"
47
- except Exception as e:
48
- return f"❌ SMS 發送失敗: {str(e)}"
49
-
50
- def call_groq_api(prompt, model="mixtral-8x7b-32768"):
51
- """調用 GROQ API"""
52
- if not api_manager.groq_api_key:
53
- return "❌ 請先設定 GROQ API Key"
54
 
55
  try:
56
- headers = {
57
- "Authorization": f"Bearer {api_manager.groq_api_key}",
58
- "Content-Type": "application/json"
59
- }
60
 
61
- data = {
62
- "messages": [
63
- {"role": "user", "content": prompt}
64
- ],
65
- "model": model,
66
- "max_tokens": 1000
 
 
67
  }
68
 
69
- response = requests.post(
70
- "https://api.groq.com/openai/v1/chat/completions",
71
- headers=headers,
72
- json=data
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
  )
74
 
75
- if response.status_code == 200:
76
- result = response.json()
77
- return result["choices"][0]["message"]["content"]
78
- else:
79
- return f"❌ GROQ API 錯誤: {response.status_code} - {response.text}"
80
-
81
- except Exception as e:
82
- return f"❌ GROQ API 調用失敗: {str(e)}"
83
-
84
- def create_gradio_interface():
85
- with gr.Blocks(title="Dynamic API Configuration Demo", theme=gr.themes.Soft()) as demo:
86
 
87
- gr.Markdown("# 🔧 Dynamic API Configuration Demo")
88
- gr.Markdown("### 動態設定 API 憑證,無需預先寫在程式中")
 
89
 
90
- with gr.Row():
91
- with gr.Column(scale=1):
92
- gr.Markdown("## 📱 API 設定")
93
-
94
- # API 憑證輸入區域
95
- with gr.Group():
96
- gr.Markdown("### Twilio 設定")
97
- twilio_sid = gr.Textbox(
98
- label="TWILIO_ACCOUNT_SID",
99
- placeholder="輸入您的 Twilio Account SID",
100
- type="password"
101
- )
102
- twilio_token = gr.Textbox(
103
- label="TWILIO_AUTH_TOKEN",
104
- placeholder="輸入您的 Twilio Auth Token",
105
- type="password"
106
- )
107
- twilio_from = gr.Textbox(
108
- label="TWILIO_FROM_NUMBER",
109
- placeholder="+1234567890",
110
- value=""
111
- )
112
-
113
- with gr.Group():
114
- gr.Markdown("### GROQ 設定")
115
- groq_key = gr.Textbox(
116
- label="GROQ_API_KEY",
117
- placeholder="輸入您的 GROQ API Key",
118
- type="password"
119
- )
120
-
121
- # 更新憑證按鈕
122
- update_btn = gr.Button("🔄 更新 API 憑證", variant="primary")
123
- status_msg = gr.Textbox(label="狀態", interactive=False)
124
-
125
- with gr.Column(scale=2):
126
- gr.Markdown("## 🚀 功能測試")
127
-
128
- # SMS 功能區域
129
- with gr.Group(visible=False) as sms_group:
130
- gr.Markdown("### 📱 SMS 發送測試")
131
- sms_to = gr.Textbox(label="收件人號碼", placeholder="+886912345678")
132
- sms_message = gr.Textbox(
133
- label="訊息內容",
134
- placeholder="輸入要發送的訊息",
135
- lines=3
136
- )
137
- sms_btn = gr.Button("發送 SMS", variant="secondary")
138
- sms_result = gr.Textbox(label="SMS 結果", interactive=False)
139
-
140
- # GROQ 功能區域
141
- with gr.Group(visible=False) as groq_group:
142
- gr.Markdown("### 🤖 GROQ AI 測試")
143
- groq_prompt = gr.Textbox(
144
- label="提示詞",
145
- placeholder="輸入您想要詢問 AI 的問題",
146
- lines=3
147
- )
148
- groq_model = gr.Dropdown(
149
- choices=[
150
- "mixtral-8x7b-32768",
151
- "llama2-70b-4096",
152
- "gemma-7b-it"
153
- ],
154
- value="mixtral-8x7b-32768",
155
- label="選擇模型"
156
- )
157
- groq_btn = gr.Button("調用 GROQ API", variant="secondary")
158
- groq_result = gr.Textbox(
159
- label="AI 回應",
160
- lines=10,
161
- interactive=False
162
- )
163
 
164
- # 事件處理
165
- update_btn.click(
166
- fn=api_manager.update_credentials,
167
- inputs=[twilio_sid, twilio_token, twilio_from, groq_key],
168
- outputs=[status_msg, sms_group, groq_group]
169
- )
170
 
171
- sms_btn.click(
172
- fn=send_sms,
173
- inputs=[sms_to, sms_message],
174
- outputs=[sms_result]
 
175
  )
176
 
177
- groq_btn.click(
178
- fn=call_groq_api,
179
- inputs=[groq_prompt, groq_model],
180
- outputs=[groq_result]
181
- )
182
 
183
- # 示例說明
184
- with gr.Row():
185
- gr.Markdown("""
186
- ## 📝 使用說明
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
187
 
188
- 1. **設定 API 憑證**: 在左側輸入您的 API 憑證
189
- 2. **點擊更新**: 系統會驗證憑證的有效性
190
- 3. **測試功能**: 憑證驗證通過後,右側功能區域會顯示
191
- 4. **安全提醒**: 所有憑證僅在當前會話中使用,不會被儲存
 
 
192
 
193
- ### 🔒 安全特性
194
- - 密碼欄位隱藏輸入內容
195
- - 憑證僅存於記憶體中
196
- - 不會記錄或儲存敏感資訊
197
- - 每次重新載入需重新輸入
198
- """)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
199
 
200
- return demo
 
 
 
 
201
 
202
  # 啟動應用程式
203
  if __name__ == "__main__":
204
- app = create_gradio_interface()
205
- app.launch(
206
- server_name="0.0.0.0",
207
- server_port=7860,
208
- share=False
209
  )
 
1
  import gradio as gr
2
+ from groq import Groq
3
  from twilio.rest import Client
4
+ import base64
5
+ import io
6
+ from PIL import Image
7
 
8
+ def encode_image(image):
9
+ """將PIL圖片編碼為base64字符串"""
10
+ buffered = io.BytesIO()
11
+ image.save(buffered, format="JPEG")
12
+ return base64.b64encode(buffered.getvalue()).decode("utf-8")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
+ def analyze_and_send_sms(
15
+ image,
16
+ groq_api_key,
17
+ account_sid,
18
+ auth_token,
19
+ from_number,
20
+ to_number,
21
+ custom_message=""
22
+ ):
23
+ """
24
+ 分析圖片並發送SMS訊息
25
 
26
+ Args:
27
+ image: 上傳的圖片
28
+ groq_api_key: Groq API金鑰
29
+ account_sid: Twilio帳戶SID
30
+ auth_token: Twilio認證令牌
31
+ from_number: Twilio虛擬手機號碼
32
+ to_number: 接收SMS的手機號碼
33
+ custom_message: 自定義訊息內容
34
+
35
+ Returns:
36
+ tuple: (圖片分析結果, SMS發送狀態)
37
+ """
 
 
38
 
39
  try:
40
+ # 步驟1: 使用Groq分析圖片
41
+ if image is None:
42
+ return "錯誤:請上傳圖片", "未發送SMS"
 
43
 
44
+ if not groq_api_key:
45
+ return "錯誤:請輸入Groq API金鑰", "未發送SMS"
46
+
47
+ # 編碼圖片
48
+ base64_image = encode_image(image)
49
+ image_content = {
50
+ "type": "image_url",
51
+ "image_url": {"url": f"data:image/jpeg;base64,{base64_image}"}
52
  }
53
 
54
+ # 設定提示詞
55
+ prompt = "解釋圖片的內容,10個字說明,使用繁體中文。"
56
+
57
+ # 建立Groq客戶端
58
+ groq_client = Groq(api_key=groq_api_key)
59
+
60
+ # 呼叫Groq API
61
+ completion = groq_client.chat.completions.create(
62
+ model="meta-llama/llama-4-scout-17b-16e-instruct",
63
+ messages=[{
64
+ "role": "user",
65
+ "content": [
66
+ {"type": "text", "text": prompt},
67
+ image_content
68
+ ]
69
+ }],
70
+ temperature=1,
71
+ max_completion_tokens=512,
72
+ top_p=1,
73
+ stream=False,
74
+ stop=None,
75
  )
76
 
77
+ # 取得圖片分析結果
78
+ analysis_result = completion.choices[0].message.content
 
 
 
 
 
 
 
 
 
79
 
80
+ # 步驟2: 發送SMS
81
+ if not all([account_sid, auth_token, from_number, to_number]):
82
+ return analysis_result, "錯誤:請填入所有Twilio設定"
83
 
84
+ # 準備SMS內容
85
+ if custom_message:
86
+ sms_body = custom_message
87
+ else:
88
+ sms_body = f"圖片分析結果:{analysis_result}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
 
90
+ # 建立Twilio客戶端
91
+ twilio_client = Client(account_sid, auth_token)
 
 
 
 
92
 
93
+ # 發送SMS
94
+ message = twilio_client.messages.create(
95
+ from_=from_number,
96
+ to=to_number,
97
+ body=sms_body
98
  )
99
 
100
+ sms_status = f"SMS發送成功!訊息SID: {message.sid}"
 
 
 
 
101
 
102
+ return analysis_result, sms_status
103
+
104
+ except Exception as e:
105
+ error_msg = f"發生錯誤: {str(e)}"
106
+ return error_msg, "SMS發送失敗"
107
+
108
+ # 建立Gradio介面
109
+ with gr.Blocks(title="圖片分析與SMS發送應用") as demo:
110
+ gr.Markdown("# 圖片分析與SMS發送應用")
111
+ gr.Markdown("上傳圖片進行AI分析,並可選擇發送分析結果到手機")
112
+
113
+ with gr.Row():
114
+ with gr.Column():
115
+ # 圖��上傳
116
+ image_input = gr.Image(
117
+ type="pil",
118
+ label="上傳圖片",
119
+ height=300
120
+ )
121
 
122
+ # Groq API設定
123
+ groq_key = gr.Textbox(
124
+ label="Groq API金鑰",
125
+ type="password",
126
+ placeholder="輸入您的Groq API金鑰"
127
+ )
128
 
129
+ with gr.Column():
130
+ # Twilio設定
131
+ account_sid = gr.Textbox(
132
+ label="Twilio Account SID",
133
+ placeholder="ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
134
+ )
135
+ auth_token = gr.Textbox(
136
+ label="Twilio Auth Token",
137
+ type="password",
138
+ placeholder="輸入您的Twilio認證令牌"
139
+ )
140
+ from_number = gr.Textbox(
141
+ label="Twilio虛擬手機號碼",
142
+ placeholder="+1xxxxxxxxxx"
143
+ )
144
+ to_number = gr.Textbox(
145
+ label="接收SMS的手機號碼",
146
+ placeholder="+886xxxxxxxxx"
147
+ )
148
+ custom_message = gr.Textbox(
149
+ label="自定義訊息內容 (選填)",
150
+ placeholder="留空則自動使用圖片分析結果",
151
+ lines=3
152
+ )
153
+
154
+ # 執行按鈕
155
+ analyze_button = gr.Button("分析圖片並發送SMS", variant="primary")
156
+
157
+ # 輸出結果
158
+ with gr.Row():
159
+ analysis_output = gr.Textbox(
160
+ label="圖片分析結果",
161
+ interactive=False
162
+ )
163
+ sms_output = gr.Textbox(
164
+ label="SMS發送狀態",
165
+ interactive=False
166
+ )
167
+
168
+ # 設定按鈕點擊事件
169
+ analyze_button.click(
170
+ fn=analyze_and_send_sms,
171
+ inputs=[
172
+ image_input,
173
+ groq_key,
174
+ account_sid,
175
+ auth_token,
176
+ from_number,
177
+ to_number,
178
+ custom_message
179
+ ],
180
+ outputs=[analysis_output, sms_output]
181
+ )
182
+
183
+ # 使用範例
184
+ gr.Markdown("""
185
+ ## 使用說明:
186
+ 1. **上傳圖片**:選擇要分析的圖片檔案
187
+ 2. **輸入Groq API金鑰**:從Groq官網取得您的API金鑰
188
+ 3. **設定Twilio參數**:
189
+ - Account SID:您的Twilio帳戶識別碼
190
+ - Auth Token:您的Twilio認證令牌
191
+ - 虛擬手機號碼:Twilio提供的發送號碼
192
+ - 接收手機號碼:要接收SMS的號碼
193
+ 4. **自定義訊息**(選填):如果留空,會自動發送圖片分析結果
194
+ 5. **點擊執行**:系統會分析圖片並發送SMS
195
 
196
+ ## 注意事項:
197
+ - 請確保Twilio帳戶有足夠餘額
198
+ - 手機號碼需包含國碼(如台灣:+886)
199
+ - API金鑰請妥善保管,勿洩露給他人
200
+ """)
201
 
202
  # 啟動應用程式
203
  if __name__ == "__main__":
204
+ demo.launch(
205
+ share=False, # 設為True可產生公開連結
206
+ debug=True,
207
+ # 移除固定端口設定,讓Gradio自動尋找可用端口
 
208
  )