Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
from huggingface_hub import InferenceClient
|
3 |
+
import requests
|
4 |
+
|
5 |
+
# Define a function to check if the given URL is valid and reachable
|
6 |
+
def is_valid_url(url):
|
7 |
+
try:
|
8 |
+
response = requests.get(url)
|
9 |
+
# Check if the response status code is 200 (OK)
|
10 |
+
return response.status_code == 200
|
11 |
+
except requests.exceptions.RequestException:
|
12 |
+
# Return False if the URL is not reachable or any other exception occurs
|
13 |
+
return False
|
14 |
+
|
15 |
+
# Streamlit app
|
16 |
+
def main():
|
17 |
+
st.title("Image Classifier")
|
18 |
+
st.write("Enter the URL of an image to classify it using Hugging Face's Inference API.")
|
19 |
+
|
20 |
+
# Input for image URL
|
21 |
+
image_url = st.text_input("Image URL")
|
22 |
+
|
23 |
+
# Display the image if the URL is valid
|
24 |
+
if image_url:
|
25 |
+
if is_valid_url(image_url):
|
26 |
+
st.image(image_url, caption='Uploaded Image', use_column_width=True)
|
27 |
+
else:
|
28 |
+
st.error("The URL is not valid or the image is not accessible. Please check the URL.")
|
29 |
+
|
30 |
+
# Button to classify the image
|
31 |
+
if st.button("Classify Image"):
|
32 |
+
if not image_url:
|
33 |
+
st.error("Please enter a URL.")
|
34 |
+
elif not is_valid_url(image_url):
|
35 |
+
st.error("Please enter a valid URL of an accessible image.")
|
36 |
+
else:
|
37 |
+
# If the URL is valid, initialize the InferenceClient with the model ID
|
38 |
+
# Replace "your-model-id" with the actual model ID you want to use
|
39 |
+
client = InferenceClient()
|
40 |
+
try:
|
41 |
+
# Perform the classification using the client
|
42 |
+
response = client.image_classification(image_url)
|
43 |
+
# Extract the label from the first prediction
|
44 |
+
label = response[0]['label'] # Adjust according to the actual output structure
|
45 |
+
st.success(f"The image was classified as: {label}")
|
46 |
+
except Exception as e:
|
47 |
+
st.error(f"Failed to classify the image: {str(e)}")
|
48 |
+
|
49 |
+
# Run the Streamlit app
|
50 |
+
if __name__ == "__main__":
|
51 |
+
main()
|