Spaces:
Running
Running
File size: 4,720 Bytes
884e760 6c74fa1 6a1229b 2d8c11a 7c8c2b6 2d8c11a 7c8c2b6 2d8c11a 7c8c2b6 2d8c11a 7c8c2b6 2d8c11a 6a1229b 7c8c2b6 2d8c11a 7c8c2b6 2d8c11a e4fdb3c 7c8c2b6 e4fdb3c 7c8c2b6 e4fdb3c 6c74fa1 7c8c2b6 a7a6db0 4af5326 7c8c2b6 6c74fa1 7c8c2b6 6c74fa1 392f702 7c8c2b6 392f702 7c8c2b6 392f702 7c8c2b6 392f702 6c74fa1 7c8c2b6 6c74fa1 7c8c2b6 a7a6db0 7c8c2b6 a7a6db0 7c8c2b6 a7a6db0 6c74fa1 2d8c11a 4af5326 7c8c2b6 4af5326 7c8c2b6 a7a6db0 2d8c11a eaaba91 a7a6db0 4af5326 a7a6db0 7c8c2b6 a7a6db0 4af5326 |
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 |
import gradio as gr
import numpy as np
import os
from PIL import Image
import requests
from io import BytesIO
import io
import base64
# استرداد مفتاح API من متغيرات البيئة
hf_token = os.environ.get("HF_TOKEN_API_DEMO") # تأكد من ضبط هذا المتغير في بيئتك
auth_headers = {"Authorization": f"Bearer {hf_token}"} # إعداد المصادقة
# تحويل الصورة إلى Base64
def convert_image_to_base64(image):
buffer = io.BytesIO()
image.save(buffer, format="PNG") # يمكن استخدام تنسيقات أخرى مثل JPEG إذا لزم الأمر
return base64.b64encode(buffer.getvalue()).decode('utf-8')
# تنزيل الصورة الناتجة من URL
def download_image(url):
response = requests.get(url)
return Image.open(BytesIO(response.content)).convert("RGB")
# استدعاء Bria API باستخدام نقطة النهاية gen_fill
def call_gen_fill_api(image, mask, api_token):
url = "https://engine.prod.bria-api.com/v1/gen_fill"
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {api_token}",
}
# تحويل الصورة والقناع إلى Base64
image_base64 = convert_image_to_base64(image)
mask_base64 = convert_image_to_base64(mask)
payload = {
"file": image_base64,
"mask_file": mask_base64,
"mask_type": "manual",
"prompt": "Erase object",
"negative_prompt": "",
"num_results": 1,
"sync": True, # معالجة متزامنة للحصول على النتيجة مباشرة
"seed": 0,
"content_moderation": False
}
response = requests.post(url, json=payload, headers=headers)
if response.status_code == 200:
result = response.json()
result_url = result.get("result_url")
if result_url:
return download_image(result_url) # تنزيل الصورة الناتجة
else:
raise Exception("No result URL found in the response.")
else:
raise Exception(f"API Error: {response.status_code} - {response.text}")
# دالة معالجة الصورة والقناع
def predict(dict):
init_image = Image.fromarray(dict['background'][:, :, :3], 'RGB')
mask = Image.fromarray(dict['layers'][0][:, :, 3], 'L') # القناع بتدرج الرمادي
api_token = hf_token # استخدم مفتاح API الخاص بك
if not api_token:
return "Error: API token is missing. Please set it in your environment variables."
try:
result_image = call_gen_fill_api(init_image, mask, api_token)
return result_image
except Exception as e:
return f"Error: {e}"
# تخصيص CSS
css = '''
.gradio-container{max-width: 1100px !important}
#image_upload{min-height:400px}
#image_upload [data-testid="image"], #image_upload [data-testid="image"] > div{min-height: 400px}
#run_button {
width: 100%;
height: 50px;
display: flex;
align-items: center;
justify-content: center;
}
#output-img img, #image_upload img {
object-fit: contain;
width: 100%;
height: auto;
}
'''
# إعداد واجهة Gradio
image_blocks = gr.Blocks(css=css, elem_id="total-container")
with image_blocks as demo:
with gr.Column(elem_id="col-container"):
gr.Markdown("## BRIA Eraser API Integration")
gr.HTML('''
<p style="margin-bottom: 10px; font-size: 94%">
This demo showcases the BRIA Gen-Fill API, allowing users to remove specific elements or objects from images.<br>
Notes:<br>
- For high-resolution images, processing time may be longer.<br>
- Ensure masks are accurate for better results.<br>
</p>
''')
with gr.Row():
with gr.Column():
image = gr.ImageEditor(
sources=["upload"],
layers=False,
transforms=[],
brush=gr.Brush(colors=["#000000"], color_mode="fixed"), # اللون الأسود كخيار فرشاة
)
with gr.Row(equal_height=True):
btn = gr.Button("Erase!", elem_id="run_button")
with gr.Column():
image_out = gr.Image(label="Output", elem_id="output-img")
# تشغيل الزر لتفعيل وظيفة التعديل
btn.click(fn=predict, inputs=[image], outputs=[image_out], api_name='run')
gr.HTML(
"""
<div class="footer">
<p>Powered by BRIA API - Gradio Demo by Hugging Face</p>
</div>
"""
)
image_blocks.queue(max_size=25, api_open=False).launch(show_api=False) |