File size: 1,977 Bytes
35992f9
 
4911caa
35992f9
31c7c46
41232ef
 
9183f10
31c7c46
c76a4f6
 
9183f10
51e15ad
 
31c7c46
 
 
 
 
 
 
 
 
 
 
c76a4f6
51e15ad
31c7c46
 
 
 
 
 
 
 
 
 
 
1b03958
31c7c46
 
 
 
 
 
 
 
 
1b03958
35992f9
31c7c46
1b03958
31c7c46
 
 
9183f10
 
 
 
 
51e15ad
9183f10
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import os
import io
import tempfile
from datetime import datetime
import PIL.Image
from google import genai
from google.genai import types
import httpx

genai_client = genai.Client(api_key=os.environ["GOOGLE_API_KEY"])

class Image_text_Generator:
    def __init__(self):
        pass

    def generate_image_with_gemini(self, prompt):
        """
        使用 Gemini ζ¨‘εž‹η”Ÿζˆεœ–η‰‡γ€‚

        參數:
        prompt (str): η”¨ζ–Όη”Ÿζˆεœ–η‰‡ηš„ζη€Ίθ©žγ€‚

        θΏ”ε›ž:
        bytes: η”Ÿζˆηš„εœ–η‰‡ηš„δΊŒι€²δ½θ³‡ζ–™οΌŒε¦‚ζžœη”Ÿζˆε€±ζ•—ε‰‡θΏ”ε›ž None。
        """
        response = genai_client.models.generate_content(
            model="gemini-2.0-flash",
            contents=prompt,
            config=types.GenerateContentConfig(response_modalities=['Text', 'Image'])
        )

        for part in response.candidates[0].content.parts:
            if part.text is not None:
                print(part.text)
            elif part.inline_data is not None:
                return part.inline_data.data
        return None

    def upload_image_to_tmp(self, user_id):
        """
        θΏ”ε›ž:
        str: δΈŠε‚³εΎŒηš„εœ–η‰‡ URLοΌŒε¦‚ζžœδΈŠε‚³ε€±ζ•—ε‰‡θΏ”ε›ž None。
        """
        try:
            # ε°‡δΊŒι€²δ½θ³‡ζ–™θ½‰ζ›η‚Ί PIL Image
            image = PIL.Image.open(io.BytesIO(image_binary))

            # ε»Ίη«‹ζš«ε­˜ζͺ”ζ‘ˆδ»₯δΎΏδΈŠε‚³
            image.save('tmp/'+user_id+'.png', format='PNG')

            # θΏ”ε›žεœ–η‰‡ηš„ι€£η΅
            return 'tmp/'+user_id+'.png'
        except Exception as e:
            print(f"εœ–η‰‡δΈŠε‚³ε€±ζ•—: {e}")
            return None

    def generate_txt_with_gemini(self, prompt,doc_url):
        doc_data = httpx.get(doc_url).content

        response = client.models.generate_content(
            model="gemini-2.0-flash",
            contents=[
                types.Part.from_bytes(data=doc_data, mime_type='application/pdf',),prompt]
        )
        
        return response.text