|
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""}) |
|
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 |
|
|
|
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() |