Spaces:
Sleeping
Sleeping
Delete Image_text_generation.py
Browse files- Image_text_generation.py +0 -57
Image_text_generation.py
DELETED
|
@@ -1,57 +0,0 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import io
|
| 3 |
-
import tempfile
|
| 4 |
-
from datetime import datetime
|
| 5 |
-
import PIL.Image
|
| 6 |
-
from google import genai
|
| 7 |
-
from google.genai import types
|
| 8 |
-
import httpx
|
| 9 |
-
|
| 10 |
-
genai_client = genai.Client(api_key=os.environ["GOOGLE_API_KEY"])
|
| 11 |
-
|
| 12 |
-
class Image_text_Generator:
|
| 13 |
-
def __init__(self, user_id):
|
| 14 |
-
|
| 15 |
-
self.user_id = user_id
|
| 16 |
-
|
| 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.data
|
| 38 |
-
return None
|
| 39 |
-
|
| 40 |
-
def upload_image_to_tmp(self, image_binary):
|
| 41 |
-
"""
|
| 42 |
-
返回:
|
| 43 |
-
str: 上傳後的圖片 URL,如果上傳失敗則返回 None。
|
| 44 |
-
"""
|
| 45 |
-
try:
|
| 46 |
-
# 將二進位資料轉換為 PIL Image
|
| 47 |
-
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 None
|
| 57 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|