Spaces:
Running
Running
File size: 2,736 Bytes
548a253 5f9552b 306f03c f0799ab 7fca710 84240eb 306f03c a644280 306f03c 7fca710 84240eb 7fca710 84240eb f0799ab 7fca710 84240eb 7fca710 f0799ab fb38e2f 84240eb 071c210 fb38e2f 84240eb f35aeab 10aec33 2e4a93b 5f9552b 10aec33 2c5448b 10aec33 4188c3b 306f03c 2c5448b 306f03c 2c5448b 306f03c 2c5448b 306f03c 84240eb |
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 |
import gradio as gr
import requests
import os
import random
from io import BytesIO
from PIL import Image
import base64
# Получение списка API ключей из переменной окружения
api_keys = os.getenv("HF_API_KEYS", "").split(",")
if not api_keys or not all(api_keys):
raise ValueError("HF_API_KEYS environment variable is not set or contains invalid keys.")
# Выбор случайного API ключа
api_key = random.choice(api_keys)
headers = {
"Authorization": f"Bearer {api_key}"
}
# Ссылка на API Hugging Face
api_url = "https://api-inference.huggingface.co/models/Salesforce/blip-image-captioning-large"
# Функция для генерации описания изображения
def caption_image(image):
if image is None:
return ""
# Преобразование изображения в байтовый формат
buffered = BytesIO()
try:
image.save(buffered, format="PNG") # Используем PNG
except Exception as e:
return f"Error: Failed to save image - {str(e)}"
image_bytes = buffered.getvalue()
# Логирование размера байтового объекта
print(f"Image size: {len(image_bytes)} bytes")
# Отправка изображения в base64
image_base64 = base64.b64encode(image_bytes).decode('utf-8')
data = {"inputs": image_base64}
response = requests.post(api_url, headers=headers, json=data, timeout=150)
# Логирование ответа
if response.status_code == 200:
return response.json()[0]['generated_text']
else:
print(f"Error: {response.status_code} - {response.text}")
return f"Error: {response.status_code} - {response.text}"
# Ссылка на файл CSS (опционально)
css_url = "https://neurixyufi-aihub.static.hf.space/style.css"
try:
response = requests.get(css_url)
css = response.text + ".gradio-container{max-width: 700px !important} h1{text-align:center}"
except requests.exceptions.RequestException as e:
print(f"Warning: Could not load CSS from {css_url}: {e}")
# Создание интерфейса Gradio
with gr.Blocks(css=css) as demo:
gr.Markdown("# Описание изображения")
with gr.Row():
with gr.Column():
image_input = gr.Image(type="pil", label="Ваше изображение")
with gr.Column():
caption_output = gr.Textbox(label="Описание")
image_input.change(fn=caption_image, inputs=image_input, outputs=caption_output)
# Запуск интерфейса
demo.launch(share=False, debug=False, show_error=False, show_api=False).queue(max_size=150) |