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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +185 -147
app.py CHANGED
@@ -1,171 +1,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
- # Groq API 設定
9
- GROQ_API_KEY = "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"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
 
11
- # Twilio 設定
12
- TWILIO_ACCOUNT_SID = "ACd7f840e0ea441d49885b4ab7a8828c46"
13
- TWILIO_AUTH_TOKEN = "b3f7af530024eb7bf68e3576f5fe3ad7"
14
- TWILIO_FROM_NUMBER = "+17623355728"
15
 
16
- def encode_image(image):
17
- """ PIL Image 轉換為 base64 編碼"""
18
- buffered = io.BytesIO()
19
- image.save(buffered, format="JPEG")
20
- return base64.b64encode(buffered.getvalue()).decode("utf-8")
 
 
 
 
 
 
 
 
 
21
 
22
- def analyze_image(image):
23
- """使Groq API 分析圖片內容"""
24
- if image is None:
25
- return "請上傳圖片"
26
 
27
  try:
28
- # 將圖片轉換為 base64
29
- base64_image = encode_image(image)
30
-
31
- # 設定圖片內容
32
- image_content = {
33
- "type": "image_url",
34
- "image_url": {"url": f"data:image/jpeg;base64,{base64_image}"}
35
  }
36
 
37
- # 初始化 Groq 客戶端
38
- client = Groq(api_key=GROQ_API_KEY)
 
 
 
 
 
39
 
40
- # 發送請求
41
- completion = client.chat.completions.create(
42
- model="meta-llama/llama-4-scout-17b-16e-instruct",
43
- messages=[{
44
- "role": "user",
45
- "content": [
46
- {
47
- "type": "text",
48
- "text": "解釋圖片的內容,10個字說明,使用繁體中文。"
49
- },
50
- image_content
51
- ]
52
- }],
53
- temperature=1,
54
- max_completion_tokens=512,
55
- top_p=1,
56
- stream=False,
57
- stop=None,
58
  )
59
 
60
- # 取出回應內容
61
- content = completion.choices[0].message.content
62
- return content
63
-
 
 
64
  except Exception as e:
65
- return f"圖片分析失敗: {str(e)}"
66
 
67
- def send_sms(phone_number, message_body):
68
- """使用 Twilio 發送簡訊"""
69
- if not phone_number or not message_body:
70
- return "請輸入手機號碼和訊息內容"
71
-
72
- try:
73
- # 初始化 Twilio 客戶端
74
- client = Client(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
 
76
- # 發送簡訊
77
- message = client.messages.create(
78
- from_=TWILIO_FROM_NUMBER,
79
- to=phone_number,
80
- body=message_body
81
  )
82
 
83
- return f"簡訊發送成功!訊息 SID: {message.sid}"
 
 
 
 
84
 
85
- except Exception as e:
86
- return f"簡訊發送失敗: {str(e)}"
87
-
88
- def process_image_and_send_sms(image, phone_number, custom_message):
89
- """處理圖片分析並發送簡訊的主要函數"""
90
- # 分析圖片
91
- analysis_result = analyze_image(image)
92
-
93
- # 準備簡訊內容
94
- if custom_message.strip():
95
- # 如果使用者有輸入自訂訊息,使用自訂訊息
96
- sms_body = custom_message
97
- else:
98
- # 如果沒有自訂訊息,使用圖片分析結果
99
- sms_body = f"圖片分析結果: {analysis_result}"
100
-
101
- # 發送簡訊
102
- sms_result = send_sms(phone_number, sms_body)
103
-
104
- return analysis_result, sms_result, sms_body
105
-
106
- # 建立 Gradio 介面
107
- with gr.Blocks(title="圖片分析與簡訊發送系統") as demo:
108
- gr.Markdown("# 圖片分析與簡訊發送系統")
109
- gr.Markdown("上傳圖片進行 AI 分析,並可選擇性發送分析結果或自訂訊息到指定手機號碼")
110
-
111
- with gr.Row():
112
- with gr.Column():
113
- # 輸入區域
114
- image_input = gr.Image(
115
- type="pil",
116
- label="上傳圖片",
117
- height=300
118
- )
119
- phone_input = gr.Textbox(
120
- label="手機號碼",
121
- placeholder="例如: +886919017732",
122
- value="+886919017732"
123
- )
124
- custom_message_input = gr.Textbox(
125
- label="自訂訊息內容 (選填)",
126
- placeholder="如果留空,將使用圖片分析結果作為簡訊內容",
127
- lines=3
128
- )
129
 
130
- with gr.Column():
131
- # 輸出區域
132
- analysis_output = gr.Textbox(
133
- label="圖片分析結果",
134
- interactive=False,
135
- lines=3
136
- )
137
- sms_result_output = gr.Textbox(
138
- label="簡訊發送結果",
139
- interactive=False,
140
- lines=2
141
- )
142
- actual_message_output = gr.Textbox(
143
- label="實際發送的訊息內容",
144
- interactive=False,
145
- lines=3
146
- )
147
-
148
- with gr.Row():
149
- analyze_btn = gr.Button("僅分析圖片", variant="secondary")
150
- send_sms_btn = gr.Button("分析圖片並發送簡訊", variant="primary")
151
-
152
- # 事件處理
153
- analyze_btn.click(
154
- fn=analyze_image,
155
- inputs=[image_input],
156
- outputs=[analysis_output]
157
- )
158
 
159
- send_sms_btn.click(
160
- fn=process_image_and_send_sms,
161
- inputs=[image_input, phone_input, custom_message_input],
162
- outputs=[analysis_output, sms_result_output, actual_message_output]
163
- )
164
 
165
- # 啟動應用
166
  if __name__ == "__main__":
167
- demo.launch(
168
- share=True, # 設為 True 可獲得公開分享連結
169
- server_name="0.0.0.0", # 允許外部訪問
170
- server_port=7860 # 指定端口
 
171
  )
 
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
  )