Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
from groq import Groq
|
3 |
+
import time
|
4 |
+
|
5 |
+
# Function to analyze an image from a URL with retry mechanism
|
6 |
+
def analyze_image(image_url, retries=3, delay=2):
|
7 |
+
for attempt in range(retries):
|
8 |
+
try:
|
9 |
+
client = Groq()
|
10 |
+
completion = client.chat.completions.create(
|
11 |
+
model="llava-v1.5-7b-4096-preview",
|
12 |
+
messages=[
|
13 |
+
{
|
14 |
+
"role": "user",
|
15 |
+
"content": [
|
16 |
+
{"type": "text", "text": "What's in this image?"},
|
17 |
+
{"type": "image_url", "image_url": {"url": image_url}},
|
18 |
+
]
|
19 |
+
}
|
20 |
+
],
|
21 |
+
temperature=1,
|
22 |
+
max_tokens=1024,
|
23 |
+
top_p=1,
|
24 |
+
stream=False,
|
25 |
+
stop=None,
|
26 |
+
)
|
27 |
+
return completion.choices[0].message.content
|
28 |
+
except Exception as e:
|
29 |
+
if attempt < retries - 1:
|
30 |
+
st.error(f"API issue encountered: {e}. Retrying in {delay} seconds...")
|
31 |
+
else:
|
32 |
+
return f"Failed after {retries} attempts. Error: {e}"
|
33 |
+
time.sleep(delay) # Wait before retrying
|
34 |
+
|
35 |
+
# Streamlit app
|
36 |
+
st.title("Image Analyzer with Groq")
|
37 |
+
st.write(
|
38 |
+
"Type image url below and Groq will describe the image! "
|
39 |
+
"To use this app, you need to provide an Groq API key, which you can get [here](https://console.groq.com/keys). "
|
40 |
+
)
|
41 |
+
st.write("Enter an image URL to describe the image.")
|
42 |
+
model_options = [
|
43 |
+
"llava-v1.5-7b-4096-preview",
|
44 |
+
"llama-3.2-1b-preview",
|
45 |
+
"llama-3.2-3b-preview",
|
46 |
+
]
|
47 |
+
with st.sidebar:
|
48 |
+
selected_model = st.selectbox("Select any Groq Model", model_options)
|
49 |
+
groq_api_key = st.text_input("Groq API Key", type="password")
|
50 |
+
if not groq_api_key:
|
51 |
+
st.info("Please add your Groq API key to continue.", icon="🗝️")
|
52 |
+
else:
|
53 |
+
# Set it as an environment variable
|
54 |
+
os.environ["GROQ_API_KEY"] = groq_api_key
|
55 |
+
# Main section
|
56 |
+
try:
|
57 |
+
image_url = st.text_input("Enter Image URL")
|
58 |
+
if image_url:
|
59 |
+
ai_response = analyze_image(image_url)
|
60 |
+
st.image(image_url, use_column_width=True)
|
61 |
+
st.write("AI's Response:", ai_response)
|
62 |
+
except Exception as e:
|
63 |
+
st.error(f"API issue encountered: {e}.")
|
64 |
+
|