Spaces:
Building
Building
File size: 4,418 Bytes
7e8a8d2 7910d5f 59098f2 7e8a8d2 59098f2 0af7a49 59098f2 0af7a49 59098f2 7e8a8d2 59098f2 7e8a8d2 ce63f30 7e8a8d2 ce63f30 7e8a8d2 ce63f30 7e8a8d2 ce63f30 7e8a8d2 ce63f30 7e8a8d2 |
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 |
from io import BytesIO
import base64
from PIL import Image
from flask import jsonify
import logging
import json
import re
import os
import requests
import google.generativeai as genai
logger = logging.getLogger(__name__)
request_counts = {}
# 核心优势
safety_settings = [
{
"category": "HARM_CATEGORY_HARASSMENT",
"threshold": "BLOCK_NONE"
},
{
"category": "HARM_CATEGORY_HATE_SPEECH",
"threshold": "BLOCK_NONE"
},
{
"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
"threshold": "BLOCK_NONE"
},
{
"category": "HARM_CATEGORY_DANGEROUS_CONTENT",
"threshold": "BLOCK_NONE"
},
]
password = os.environ['password']
def authenticate_request(request):
auth_header = request.headers.get('Authorization')
if not auth_header:
return False, jsonify({'error': '缺少Authorization请求头'}), 401
try:
auth_type, pass_word = auth_header.split(' ', 1)
except ValueError:
return False, jsonify({'error': 'Authorization请求头格式错误'}), 401
if auth_type.lower() != 'bearer':
return False, jsonify({'error': 'Authorization类型必须为Bearer'}), 401
if pass_word != password:
return False, jsonify({'error': '未授权'}), 401
return True, None, None
def get_gen_model(api_key, model, temperature, max_tokens):
genai.configure(api_key=api_key)
generation_config = {
"temperature": temperature,
"max_output_tokens": max_tokens
}
gen_model = genai.GenerativeModel(
model_name=model,
generation_config=generation_config,
safety_settings=safety_settings
)
return gen_model
def process_messages_for_gemini(messages):
gemini_history = []
for message in messages:
role = message.get('role')
content = message.get('content')
if isinstance(content, str):
if role == 'system':
gemini_history.append({"role": "user", "parts": [content]})
elif role == 'user':
gemini_history.append({"role": "user", "parts": [content]})
elif role == 'assistant':
gemini_history.append({"role": "model", "parts": [content]})
elif isinstance(content, list):
parts = []
for item in content:
if item.get('type') == 'text':
parts.append(item.get('text'))
elif item.get('type') == 'image_url':
image_data = item.get('image_url', {}).get('url', '')
if image_data.startswith('data:image/'):
try:
image_type = image_data.split(';')[0].split('/')[1].upper()
base64_image = image_data.split(';base64,')[1]
image = Image.open(BytesIO(base64.b64decode(base64_image)))
if image.mode != 'RGB':
image = image.convert('RGB')
if image.width > 2048 or image.height > 2048:
image.thumbnail((2048, 2048))
output_buffer = BytesIO()
image.save(output_buffer, format=image_type)
output_buffer.seek(0)
parts.append(image)
except Exception as e:
logger.error(f"Error processing image: {e}")
return [], None, (jsonify({'error': 'Invalid image data'}), 400)
else:
return [], None, (jsonify({'error': 'Invalid image URL format'}), 400)
if role in ['user', 'system']:
gemini_history.append({"role": "user", "parts": parts})
elif role == 'assistant':
gemini_history.append({"role": "model", "parts": parts})
else:
return [], None, (jsonify({'error': f'Invalid role: {role}'}), 400)
if gemini_history:
user_message = gemini_history[-1]
gemini_history = gemini_history[:-1]
else:
user_message = {"role": "user", "parts": [""]}
return gemini_history, user_message, None |