appzmaz / app.py
yyasso's picture
Update app.py
6ba9b2a verified
import gradio as gr
from groq import Groq
import os
from PIL import Image
API_KEY = "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"
client = Groq(api_key=API_KEY)
# مسار لحفظ الصور المرفوعة
UPLOAD_FOLDER = "./uploaded_images"
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
# صورة رمزية للبوت
BOT_AVATAR = "https://shfra.netlify.app/9121959e-df49-4796-a8b2-eb85f6368976.png"
def save_and_process_image(image_path):
"""حفظ الصورة المرفوعة ومعالجتها"""
image = Image.open(image_path)
saved_image_path = os.path.join(UPLOAD_FOLDER, os.path.basename(image_path))
image.save(saved_image_path)
return saved_image_path
def chat_with_gpt(user_input, history, image):
history = history or []
messages = [
{"role": "system", "content": "Your name is shfraAI, helpful AI assistant that can answer questions about images. You can analyze images and provide detailed descriptions and answers based on their content.Developed by hcoding."},
{"role": "user", "content": user_input}
]
# معالجة الصورة إذا تم رفعها
if image:
saved_image_path = save_and_process_image(image)
messages.append({"role": "user", "content": f"![Uploaded Image]({saved_image_path})"})
image_html = f"<img src='{saved_image_path}' style='max-width: 200px; max-height: 200px;'>"
history.append(("User uploaded an image:", image_html))
# استدعاء نموذج الذكاء الاصطناعي
completion = client.chat.completions.create(
model="llama-3.3-70b-versatile",
messages=messages,
temperature=1,
max_tokens=1024,
top_p=1,
stream=True,
stop=None,
)
# تجميع الرد من البوت
response = ""
for chunk in completion:
if chunk.choices[0].delta.content:
response += chunk.choices[0].delta.content
# تحديث السجل مع عرض صورة رمزية للبوت
history.append((f"You: {user_input}", None)) # رسالة المستخدم
history.append((None, f"<img src='{BOT_AVATAR}' style='width: 50px; border-radius: 50%;'> {response}")) # رسالة البوت
return history, history, None # إعادة تعيين الحقل الخاص بالصورة إلى None
with gr.Blocks() as demo:
with gr.Row():
chatbot = gr.Chatbot(label="shfraAI Chat", elem_id="chatbox")
with gr.Row():
user_input = gr.Textbox(label="Input", placeholder="Type your message here...", scale=5)
submit_button = gr.Button("Send")
with gr.Row():
image_input = gr.Image(label="Choose Image", type="filepath")
state = gr.State() # لتخزين التاريخ
# حدث زر الإرسال
submit_button.click(chat_with_gpt, inputs=[user_input, state, image_input], outputs=[chatbot, state, image_input])
demo.launch()