File size: 5,407 Bytes
19e65d2
 
 
 
 
a66ef29
7d3ad94
b6ea73c
19e65d2
21fd6e1
 
8b900d9
87e0d6d
 
 
 
 
 
8b900d9
19e65d2
 
 
 
 
 
 
 
8b900d9
21fd6e1
19e65d2
 
 
 
 
 
21fd6e1
19e65d2
 
7642626
 
19e65d2
 
 
7642626
19e65d2
 
 
8b900d9
21fd6e1
19e65d2
7642626
 
 
19e65d2
 
 
21fd6e1
a66ef29
 
 
 
7d3ad94
a66ef29
fd1a069
a66ef29
 
 
 
 
 
 
21fd6e1
8b900d9
b6ea73c
 
 
 
 
 
 
7642626
b6ea73c
 
 
 
 
21fd6e1
b6ea73c
21fd6e1
a6bd9bf
 
 
 
 
 
 
b6ea73c
 
 
 
 
 
 
 
 
21fd6e1
b6ea73c
8b900d9
21fd6e1
8b900d9
a66ef29
 
8b900d9
7d3ad94
5a6435d
8b900d9
a66ef29
 
 
 
 
 
 
 
 
 
21fd6e1
8b900d9
 
30ad4b1
21fd6e1
19e65d2
8b900d9
7642626
19e65d2
 
21fd6e1
 
 
 
 
 
8b900d9
 
 
21fd6e1
 
19e65d2
 
 
 
 
 
 
54f73b8
0c20e1a
19e65d2
 
 
 
 
 
 
 
 
 
 
21fd6e1
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
import os
import tempfile
import json
import re
import gradio as gr
import google.generativeai as genai
import random
from PIL import Image # Thêm dòng này

print("Google Generative AI SDK version:", genai.__version__)

API_KEYS = [
    "AIzaSyBAZ1Zm2KCZHlmVKPgVf2Cch0c-0YJfJVg",
    "AIzaSyCWiMI9o4riw_9ucsSrIyModT3YD3a8BsU",
    "AIzaSyBJFwj-Wzq-kLOLlsodR5Lwf4qIT6d2dJQ",
    "AIzaSyAPFCgH8uSjANmPRF9iHYIYcneTOod8Qi0",
    "AIzaSyBbK-1P3JD6HPyE3QLhkOps6_-Xo3wUFbs"
    
]

key_index = 0
def get_next_key():
    global key_index
    key = API_KEYS[key_index % len(API_KEYS)]
    key_index += 1
    return key


# ==== JSON EXTRACTION ====
def extract_json(text):
    match = re.search(r"```json\s*(.*?)\s*```", text, re.IGNORECASE | re.DOTALL)
    if match:
        json_text = match.group(1).strip()
    else:
        json_text = text.strip()

    try:
        return json.loads(json_text)
    except Exception:
        first, last = json_text.find("{"), json_text.rfind("}")
        if first != -1 and last != -1 and last > first:
            try:
                return json.loads(json_text[first:last+1])
            except Exception:
                pass
        return {"raw_response": text}


# ==== MAIN PROCESS ====
def process_image(image, prompt):
    temp_file = None
    uploaded_file = None

    try:
        print(f"Received image: {type(image)}")
        print(f"Received prompt: {prompt}")

        api_key = random.choice(API_KEYS)
        if not api_key:
            return "ERROR: Missing GOOGLE_API_KEY.", None
        genai.configure(api_key=api_key)
        model_name = "gemini-2.5-flash"
        model = genai.GenerativeModel(model_name=model_name,
                                      generation_config={})

        # # Create RAG store
        # RAG_STORE_NAME = "default_rag_store"
        # try:
        #     genai.create_rag_store(name=RAG_STORE_NAME)
        # except Exception as e:
        #     print("(Info) RAG store exists:", e)

        # Create temp file
        COMPRESSION_QUALITY = 80

        # === KHỐI CODE THAY THẾ ===
        # Tạo tệp tạm thời với suffix là .jpeg
        with tempfile.NamedTemporaryFile(delete=False, suffix=".jpeg") as tmp:
            
            # 1. Mở hình ảnh bằng Pillow (xử lý các loại input khác nhau)
            if hasattr(image, "save"):
                # Trường hợp input đã là đối tượng Pillow Image
                img = image
            elif isinstance(image, str) and os.path.exists(image):
                # Trường hợp input là đường dẫn tệp
                img = Image.open(image)
            else:
                # Trường hợp input không được hỗ trợ
                raise ValueError(f"Unsupported image type: {type(image)}")
            # KIỂM TRA VÀ CHUYỂN ĐỔI CHẾ ĐỘ MÀU TỪ RGBA SANG RGB
            if img.mode == 'RGBA':
                # Tạo một nền trắng (hoặc bất kỳ màu nào bạn muốn)
                background = Image.new('RGB', img.size, (255, 255, 255))
                # Dán hình ảnh RGBA lên trên nền RGB
                background.paste(img, mask=img.split()[3]) # img.split()[3] là kênh Alpha
                img = background
            # 2. Giảm Chất Lượng (quality=80) và Lưu tệp vào tệp tạm thời
            # Lưu dưới định dạng JPEG để tối ưu hóa việc nén
            img.save(
                tmp.name, 
                format='JPEG', 
                optimize=True, 
                quality=COMPRESSION_QUALITY
            )
            
            temp_file = tmp.name
        # ===========================
        print("Temp file:", temp_file)

        # Upload file
        #uploaded_file = client.files.upload(file=temp_file)
        uploaded_file = genai.upload_file(path=temp_file, mime_type="image/jpeg")
        print("Uploaded:", uploaded_file.name)
        

        # === GENERATE CONTENT ====
        response = model.generate_content([prompt, uploaded_file])
        # response = model.generate_content(
        #     contents=[
        #         prompt,
        #         uploaded_file   # file reference
        #     ],
        #     request_options={
        #         "temperature": 0.2
        #     }
        # )

        print("Raw response:", response.text[:200], "...")

        return extract_json(response.text) 

    except Exception as e:
        print("Error:", e)
        import traceback; traceback.print_exc()
        return {"error": str(e)}

    finally:
        if temp_file and os.path.exists(temp_file):
            os.remove(temp_file)
        if uploaded_file:
            try:
                genai.delete_file(uploaded_file.name)
            except:
                pass


# ==== GRADIO UI ====
demo = gr.Interface(
    fn=process_image,
    inputs=[
        gr.File(label="Upload Image", file_types=["image"]),
        gr.Textbox(lines=5, placeholder="Enter your prompt here...", label="Prompt"),
    ],
    outputs=gr.JSON(label="Response"),
    title="OCR & Analyzer (RAG Enhanced)",
    description="Upload an image + prompt → analyze with RAG store",
    flagging_mode="never",
)

demo.api_name = "/predict"

if __name__ == "__main__":
    demo.launch(
        server_name="0.0.0.0",
        server_port=int(os.getenv("PORT", "7860")),
        show_error=True,
        debug=True,
    )