Arafath10's picture
Update app.py
1d1c3bb verified
Raw
History Blame Contribute Delete
5.94 kB
import gradio as gr
import os
import PIL.Image
css = """footer {visibility: hidden}
"""
import google.generativeai as genai
import pandas as pd
from bs4 import BeautifulSoup
import requests
def get_image(keyword):
headers = {
"User-Agent":
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36"
}
params = {
"q": keyword,"count":200
#"cc": "us" # language/country of the search
}
html = requests.get('https://www.bing.com/images/search', params=params, headers=headers)
soup = BeautifulSoup(html.text, 'lxml')
data=[]
for result in soup.select('.iusc'):
try:
img = str(result).split(",")
temp ={}
for i in img[4:11]:
if '"t"' in i:
i = i.replace('"t":"',"")
temp["title"]=(i.replace('"',""))
if '"purl"' in i:
i = i.replace('"purl":"',"")
temp["page_url"]=(i.replace('"',""))
if '"murl"' in i:
i = i.replace('"murl":"',"")
temp["image_url"]=(i.replace('"',""))
if '"turl"' in i:
i = i.replace('"turl":"',"")
temp["thumbnail"]=(i.replace('"',""))
if temp!={}:
data.append(temp)
except:
continue
print(data)
# Convert data list to HTML string for 3-column view
head_html = '<h1 style="color: white; font-size: 24px; font-family: Arial, sans-serif; border-bottom: 2px solid #333; padding-bottom: 10px; text-shadow: 0 0 8px rgba(255, 255, 255, 0.8), 0 0 10px rgba(255, 255, 255, 0.7), 0 0 12px rgba(0, 0, 255, 0.6), 0 0 14px rgba(0, 0, 255, 0.5), 0 0 16px rgba(0, 0, 255, 0.4), 0 0 18px rgba(0, 0, 255, 0.3);">External Links</h1>'
html_str = head_html + '<div style="display: grid; grid-template-columns: repeat(5, minmax(180px, 1fr)); gap: 20px; padding: 20px;">'
for item in data:
try:
item_html = '<div style="border: 1px solid #ddd; border-radius: 8px; overflow: hidden; box-shadow: 0 4px 6px rgba(0,0,0,0.1);"><a href="{image_url}" style="display: block; overflow: hidden;"><img src="{thumbnail}" alt="{title}" style="width: 100%; height: 180px; object-fit: cover; transition: transform 0.2s;"></a><div style="padding: 15px;"><a href="{page_url}" style="text-decoration: none;color: blue;"><h2 style="font-size: 14px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;color: blue;">Learn More</h2></a></div></div>'.format(**item)
html_str += item_html
except Exception as e:
print(f"Error processing item: {e}")
continue
html_str += '</div>' + '<style>img:hover { transform: scale(1.05); }</style>'
return html_str
async def respond(message,image, chat_history):
try:
html_data = get_image(message)
except:
html_data = "Try new keywords"
iterate = True
while iterate:
try:
secret = os.environ["secret"]
genai.configure(api_key=secret)
model_vision = genai.GenerativeModel('gemini-pro-vision')
model_text = genai.GenerativeModel('gemini-pro')
if image==None or image=="":
response = model_text.generate_content(message)
print(response)
try:
chat_history.append((message,response.text))
except:
chat_history.append((message,str(response)))
chat_history.append((None,html_data))
#return "", chat_history
else:
img = PIL.Image.open(image)
response = model_vision.generate_content([message, img])
print(response)
try:
chat_history.append((message,response.text))
except:
chat_history.append((message,str(response)))
chat_history.append((None,html_data))
iterate = False
except:
print("error")
continue
return "", chat_history
def upload_file_to_chat(file_path,chat_history):
chat_history.append(("<img src='https://cdn.dribbble.com/users/4625326/screenshots/19602645/media/a38d52a0a465a2265aee186316cfa590.gif'> <br><br> your file uploaded",None))
return chat_history
css = """footer {visibility: hidden}
"""
with gr.Blocks(theme=gr.themes.Soft(),title="AI-search-engine",css=css) as demo:
with gr.Row():
chatbot = gr.Chatbot([[None,'Hi there, what brings you here today?']],avatar_images=("https://cdnl.iconscout.com/lottie/premium/thumb/user-profile-5568736-4644453.gif","https://cdn.dribbble.com/users/77598/screenshots/16399264/media/d86ceb1ad552398787fb76f343080aa6.gif"),height=600,show_label=False,show_copy_button=True,show_share_button=True,likeable=True,layout="panel")
with gr.Row():
msg = gr.Textbox(scale=3,show_label=False,placeholder="type anything and press enter")
upload_file = gr.UploadButton("Upload a image",type="filepath",scale=1, file_types=["image","csv"])
upload_file.upload(upload_file_to_chat,[upload_file,chatbot], [chatbot])
msg.submit(respond, [msg, upload_file,chatbot], [msg, chatbot])
demo.launch()