-
Notifications
You must be signed in to change notification settings - Fork 57
feat: add image upload support with compression and increase body limit #39
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Hieuslecong
wants to merge
3
commits into
ntthanh2603:main
Choose a base branch
from
Hieuslecong:feature/gemini-vision-support
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,95 @@ | ||
| import io | ||
| import json | ||
| import base64 | ||
| import requests | ||
| import sys | ||
| from PIL import Image as PILImage | ||
|
|
||
| # Configuration | ||
| API_URL = "http://localhost:4981/gemini/v1beta/models/gemini-advanced:generateContent" | ||
|
|
||
| def encode_image(image_path, max_size=(1024, 1024), quality=80): | ||
| """Đọc file ảnh, nén/resize xuống và mã hóa thành Base64""" | ||
| try: | ||
| # Mở ảnh bằng Pillow | ||
| img = PILImage.open(image_path) | ||
|
|
||
| # Chuyển đổi sang RGB nếu là RGBA (tránh lỗi khi lưu JPEG) | ||
| if img.mode in ("RGBA", "P"): | ||
| img = img.convert("RGB") | ||
|
|
||
| # Resize nếu ảnh quá lớn (giữ tỉ lệ) | ||
| img.thumbnail(max_size, PILImage.Resampling.LANCZOS) | ||
|
|
||
| # Lưu vào bộ nhớ đệm dạng byte với định dạng JPEG để nén dung lượng cao | ||
| buffer = io.BytesIO() | ||
| img.save(buffer, format="JPEG", quality=quality, optimize=True) | ||
|
|
||
| return base64.b64encode(buffer.getvalue()).decode('utf-8') | ||
| except ImportError: | ||
| print("Lỗi: Bạn cần cài đặt thư viện Pillow để nén ảnh. Chạy lệnh: pip install Pillow") | ||
| sys.exit(1) | ||
| except Exception as e: | ||
| print(f"Lỗi khi xử lý ảnh: {e}") | ||
| sys.exit(1) | ||
|
|
||
| def main(): | ||
| # Cần ít nhất 2 tham số: tên script, đường dẫn ảnh, và câu hỏi | ||
| if len(sys.argv) < 3: | ||
| print("Sử dụng: python3 demo_ask_image.py <đường_dẫn_tới_ảnh> \"<câu_hỏi_của_bạn>\"") | ||
| print("Ví dụ: python3 demo_ask_image.py 5_3d_visualization.png \"Trục X đại diện cho cái gì?\"") | ||
| sys.exit(1) | ||
|
|
||
| image_path = sys.argv[1] | ||
| prompt_text = sys.argv[2] # Câu hỏi từ người dùng | ||
|
|
||
| print(f"Bức ảnh: {image_path}") | ||
| print(f"Câu hỏi: {prompt_text}") | ||
| print("Đang xủ lý và tải ảnh lên...") | ||
|
|
||
| base64_image = encode_image(image_path) | ||
|
|
||
| # Khởi tạo Payload gửi đến Go Server | ||
| payload = { | ||
| "contents": [ | ||
| { | ||
| "parts": [ | ||
| {"text": prompt_text}, | ||
| { | ||
| "inlineData": { | ||
| "mimeType": "image/jpeg", # Định dạng ảnh chung | ||
| "data": base64_image | ||
| } | ||
| } | ||
| ] | ||
| } | ||
| ] | ||
| } | ||
|
|
||
| headers = { | ||
| "Content-Type": "application/json" | ||
| } | ||
|
|
||
| print(f"Đang chờ Gemini trả lời...\n") | ||
| try: | ||
| response = requests.post(API_URL, headers=headers, data=json.dumps(payload)) | ||
| response.raise_for_status() | ||
|
|
||
| result = response.json() | ||
|
|
||
| print("============== GEMINI TRẢ LỜI ==============") | ||
| try: | ||
| answer = result['candidates'][0]['content']['parts'][0]['text'] | ||
| print(answer) | ||
| except (KeyError, IndexError) as e: | ||
| print("Cấu trúc phản hồi không khớp dự kiến. Dữ liệu gốc:") | ||
| print(json.dumps(result, indent=2)) | ||
| print("===========================================\n") | ||
|
|
||
| except requests.exceptions.RequestException as e: | ||
| print(f"Lỗi gọi API: {e}") | ||
| if hasattr(e, 'response') and e.response is not None: | ||
| print(f"Chi tiết: {e.response.text}") | ||
|
|
||
| if __name__ == "__main__": | ||
| main() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,92 @@ | ||
| import io | ||
| import json | ||
| import base64 | ||
| import requests | ||
| import sys | ||
| from PIL import Image as PILImage | ||
|
|
||
| # Configuration | ||
| API_URL = "http://localhost:4981/gemini/v1beta/models/gemini-advanced:generateContent" | ||
|
|
||
| def encode_image(image_path, max_size=(1024, 1024), quality=80): | ||
| """Đọc file ảnh, nén/resize xuống và mã hóa thành Base64""" | ||
| try: | ||
| # Mở ảnh bằng Pillow | ||
| img = PILImage.open(image_path) | ||
|
|
||
| # Chuyển đổi sang RGB nếu là RGBA (tránh lỗi khi lưu JPEG) | ||
| if img.mode in ("RGBA", "P"): | ||
| img = img.convert("RGB") | ||
|
|
||
| # Resize nếu ảnh quá lớn (giữ tỉ lệ) | ||
| img.thumbnail(max_size, PILImage.Resampling.LANCZOS) | ||
|
|
||
| # Lưu vào bộ nhớ đệm dạng byte với định dạng JPEG để nén dung lượng cao | ||
| buffer = io.BytesIO() | ||
| img.save(buffer, format="JPEG", quality=quality, optimize=True) | ||
|
|
||
| return base64.b64encode(buffer.getvalue()).decode('utf-8') | ||
| except ImportError: | ||
| print("Lỗi: Bạn cần cài đặt thư viện Pillow để nén ảnh. Chạy lệnh: pip install Pillow") | ||
| sys.exit(1) | ||
| except Exception as e: | ||
| print(f"Lỗi khi xử lý ảnh: {e}") | ||
| sys.exit(1) | ||
|
|
||
| def main(): | ||
| if len(sys.argv) < 2: | ||
| print("Sử dụng: python demo_upload.py <đường_dẫn_tới_ảnh>") | ||
| print("Ví dụ: python demo_upload.py 5_3d_visualization.png") | ||
| sys.exit(1) | ||
|
|
||
| image_path = sys.argv[1] | ||
| prompt_text = "Mô tả chi tiết bức ảnh này." | ||
|
|
||
| print(f"Đang chuẩn bị gửi ảnh: {image_path}") | ||
| base64_image = encode_image(image_path) | ||
|
|
||
| # Khởi tạo Payload gửi đến Go Server (chuẩn Gemini/Vertex AI) | ||
| payload = { | ||
| "contents": [ | ||
| { | ||
| "parts": [ | ||
| {"text": prompt_text}, | ||
| { | ||
| "inlineData": { | ||
| "mimeType": "image/jpeg", # Ảnh luôn được chuyển đổi sang định dạng JPEG để nén. | ||
| "data": base64_image | ||
| } | ||
| } | ||
| ] | ||
| } | ||
| ] | ||
| } | ||
|
|
||
| headers = { | ||
| "Content-Type": "application/json" | ||
| } | ||
|
|
||
| print(f"Đang gửi yêu cầu tới {API_URL}...") | ||
| try: | ||
| response = requests.post(API_URL, headers=headers, data=json.dumps(payload)) | ||
| response.raise_for_status() # Báo lỗi nếu server trả về mã lỗi (500, 400...) | ||
|
|
||
| result = response.json() | ||
|
|
||
| print("\n--- Gemini Trả Lời ---") | ||
| # Trích xuất nội dung văn bản từ kết quả trả về | ||
| try: | ||
| answer = result['candidates'][0]['content']['parts'][0]['text'] | ||
| print(answer) | ||
| except (KeyError, IndexError) as e: | ||
| print("Cấu trúc phản hồi không khớp dự kiến. Dữ liệu gốc:") | ||
| print(json.dumps(result, indent=2)) | ||
| print("------------------------\n") | ||
|
|
||
| except requests.exceptions.RequestException as e: | ||
| print(f"Lỗi gọi API: {e}") | ||
| if hasattr(e, 'response') and e.response is not None: | ||
| print(f"Chi tiết response: {e.response.text}") | ||
|
|
||
| if __name__ == "__main__": | ||
| main() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.