CoolFace
Apppublic

yuna456789/Linebot

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
Image_text_generation.py58 linesDownload Raw Back to root
1import os2import io3import tempfile4from datetime import datetime5import PIL.Image6from google import genai7from google.genai import types8import httpx9 10genai_client = genai.Client(api_key=os.environ["GOOGLE_API_KEY"])11 12class Image_text_Generator:13    def __init__(self, user_id):14        15        self.user_id = user_id16        17    def generate_image_with_gemini(self, prompt):18        """19        使用 Gemini 模型生成圖片。20 21        參數:22        prompt (str): 用於生成圖片的提示詞。23 24        返回:25        bytes: 生成的圖片的二進位資料,如果生成失敗則返回 None。26        """27        response = genai_client.models.generate_content(28            model="gemini-2.0-flash-exp",29            contents=prompt,30            config=types.GenerateContentConfig(response_modalities=['Text', 'Image'])31        )32 33        for part in response.candidates[0].content.parts:34            if part.text is not None:35                print(part.text)36            elif part.inline_data is not None:37                return part.inline_data.data38        return None39 40    def upload_image_to_tmp(self, image_binary):41        """42        返回:43        str: 上傳後的圖片 URL,如果上傳失敗則返回 None。44        """45        try:46            # 將二進位資料轉換為 PIL Image47            image = PIL.Image.open(io.BytesIO(image_binary))48 49            # 建立暫存檔案以便上傳50            image.save('static/'+self.user_id+'.png', format='PNG')51 52            # 返回圖片的連結53            return 'static/'+self.user_id+'.png'54        except Exception as e:55            print(f"圖片上傳失敗: {e}")56            return None57        58