CoolFace
Apppublic

eeBill/groqAPI_poto

sourceHugging Faceotherupdated 1y agoView on Hugging Face
0likes
app.py160 linesDownload Raw Back to root
1import gradio as gr2from groq import Groq3import base644import io5from PIL import Image6import traceback7 8def encode_image(image):9    """將 PIL Image 編碼為 base64"""10    buffered = io.BytesIO()11    image.save(buffered, format="JPEG")12    return base64.b64encode(buffered.getvalue()).decode("utf-8")13 14def analyze_image(image, prompt, api_key):15    """分析圖片的主要函數"""16    try:17        # 檢查輸入18        if not api_key:19            return "錯誤:請輸入 API Key"20        21        if not image:22            return "錯誤:請上傳圖片"23            24        if not prompt.strip():25            return "錯誤:請輸入 prompt"26        27        # 編碼圖片28        base64_image = encode_image(image)29        image_content = {30            "type": "image_url",31            "image_url": {"url": f"data:image/jpeg;base64,{base64_image}"}32        }33        34        # 建立 Groq 客戶端35        client = Groq(api_key=api_key)36        37        # 發送請求38        completion = client.chat.completions.create(39            model="meta-llama/llama-4-scout-17b-16e-instruct",40            messages=[{41                "role": "user",42                "content": [43                    {44                        "type": "text",45                        "text": prompt46                    },47                    image_content48                ]49            }],50            temperature=1,51            max_completion_tokens=512,52            top_p=1,53            stream=False,54            stop=None,55        )56        57        # 取出回應內容58        content = completion.choices[0].message.content59        return content60        61    except Exception as e:62        error_msg = f"發生錯誤:{str(e)}\n\n詳細錯誤訊息:\n{traceback.format_exc()}"63        return error_msg64 65# 建立 Gradio 介面66def create_interface():67    with gr.Blocks(title="Groq 圖片分析工具", theme=gr.themes.Soft()) as demo:68        gr.Markdown("# 🖼️ Groq 圖片分析工具")69        gr.Markdown("使用 Groq API 的 LLaMA 模型來分析和說明圖片內容")70        71        with gr.Row():72            with gr.Column(scale=1):73                # 輸入區域74                gr.Markdown("## 📝 輸入設定")75                76                api_key_input = gr.Textbox(77                    label="Groq API Key",78                    placeholder="請輸入您的 Groq API Key (例: gsk_...)",79                    type="password",80                    lines=181                )82                83                image_input = gr.Image(84                    label="上傳圖片",85                    type="pil",86                    height=30087                )88                89                prompt_input = gr.Textbox(90                    label="Prompt (提示詞)",91                    placeholder="請輸入您想要 AI 如何分析這張圖片...",92                    lines=3,93                    value="幫我說明這張圖片,使用繁體中文"94                )95                96                analyze_btn = gr.Button(97                    "🔍 分析圖片", 98                    variant="primary",99                    size="lg"100                )101                102            with gr.Column(scale=1):103                # 輸出區域104                gr.Markdown("## 🤖 AI 分析結果")105                106                output_text = gr.Textbox(107                    label="分析結果",108                    lines=15,109                    max_lines=20,110                    show_copy_button=True,111                    placeholder="AI 的分析結果將會顯示在這裡..."112                )113        114        # 範例區域115        with gr.Row():116            gr.Markdown("## 💡 使用說明")117            gr.Markdown("""118            1. **輸入 API Key**:請先到 [Groq Console](https://console.groq.com/) 申請免費的 API Key119            2. **上傳圖片**:支援 JPG、PNG 等常見圖片格式120            3. **輸入 Prompt**:告訴 AI 您希望如何分析這張圖片121            4. **點擊分析**:等待 AI 處理並回傳結果122            123            **範例 Prompt:**124            - 幫我說明這張圖片,使用繁體中文125            - 描述這張圖片中的主要物件和場景126            - 分析這張圖片的構圖和色彩127            - 這張圖片傳達了什麼情感或氛圍?128            """)129        130        # 按鈕點擊事件131        analyze_btn.click(132            fn=analyze_image,133            inputs=[image_input, prompt_input, api_key_input],134            outputs=output_text,135            show_progress=True136        )137        138        # 範例139        gr.Examples(140            examples=[141                [None, "請詳細描述這張圖片中的所有內容,包括人物、物品、環境等,使用繁體中文回答", ""],142                [None, "分析這張圖片的藝術風格和構圖特點", ""],143                [None, "這張圖片適合用在什麼場合或用途?", ""],144                [None, "描述圖片中的色彩搭配和視覺效果", ""]145            ],146            inputs=[image_input, prompt_input, api_key_input],147            label="範例 Prompt"148        )149    150    return demo151 152# 啟動應用程式153if __name__ == "__main__":154    demo = create_interface()155    demo.launch(156        share=True,  # 設為 True 可產生公開連結157        server_name="0.0.0.0",  # 允許外部連接158        server_port=7860,  # 指定端口159        show_error=True  # 顯示詳細錯誤訊息160    )