yeftakun commited on
Commit
ef5ff29
1 Parent(s): f119831

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +40 -36
app.py CHANGED
@@ -4,7 +4,6 @@ from PIL import Image
4
  import requests
5
  from io import BytesIO
6
  import json
7
- from flask import Flask, request, jsonify
8
 
9
  # Load the model and processor
10
  processor = ViTImageProcessor.from_pretrained('AdamCodd/vit-base-nsfw-detector')
@@ -26,52 +25,57 @@ def predict_image(image):
26
  except Exception as e:
27
  return str(e)
28
 
29
- # Streamlit app
30
  st.title("NSFW Image Classifier")
31
 
32
- # Display API usage instructions
33
- st.write("You can use this app with the API endpoint below. Send a POST request with the image URL to get classification.")
34
- st.write("Example URL to use with curl:")
35
- st.code("curl -X POST https://huggingface.co/spaces/yeftakun/nsfw_api2/api/classify -H 'Content-Type: application/json' -d '{\"image_url\": \"https://example.jpg\"}'")
36
-
37
  # URL input for UI
38
- image_url = st.text_input("Enter Image URL", placeholder="Enter image URL here")
39
- if image_url:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  try:
41
- # Load image from URL
42
- response = requests.get(image_url)
43
  image = Image.open(BytesIO(response.content))
44
  st.image(image, caption='Image from URL', use_column_width=True)
45
  st.write("")
46
  st.write("Classifying...")
47
 
48
- # Predict and display result
49
  prediction = predict_image(image)
50
  st.write(f"Predicted Class: {prediction}")
51
  except Exception as e:
52
  st.write(f"Error: {e}")
53
 
54
- # API Endpoint using Flask
55
- app = Flask(__name__)
56
-
57
- @app.route('/api/classify', methods=['POST'])
58
- def classify():
59
- data = request.json
60
- image_url = data.get('image_url')
61
-
62
- if not image_url:
63
- return jsonify({"error": "Image URL is required"}), 400
64
-
65
- try:
66
- # Load image from URL
67
- response = requests.get(image_url)
68
- image = Image.open(BytesIO(response.content))
69
-
70
- # Predict image
71
- prediction = predict_image(image)
72
- return jsonify({"predicted_class": prediction})
73
- except Exception as e:
74
- return jsonify({"error": str(e)}), 500
75
-
76
- if __name__ == '__main__':
77
- app.run(port=5000)
 
4
  import requests
5
  from io import BytesIO
6
  import json
 
7
 
8
  # Load the model and processor
9
  processor = ViTImageProcessor.from_pretrained('AdamCodd/vit-base-nsfw-detector')
 
25
  except Exception as e:
26
  return str(e)
27
 
28
+ # Streamlit app for UI and API endpoint
29
  st.title("NSFW Image Classifier")
30
 
 
 
 
 
 
31
  # URL input for UI
32
+ image_url_ui = st.text_input("Enter Image URL", placeholder="Enter image URL here")
33
+
34
+ # API endpoint for classification (POST request)
35
+ @st.experimental_singleton # Ensure a single instance for performance
36
+ def api_endpoint():
37
+ if request.method == 'POST':
38
+ data = request.json
39
+ if 'image_url' in data:
40
+ try:
41
+ image_url = data['image_url']
42
+ # Load image from URL
43
+ response = requests.get(image_url)
44
+ image = Image.open(BytesIO(response.content))
45
+
46
+ # Predict and return result as JSON
47
+ prediction = predict_image(image)
48
+ return json.dumps({'predicted_class': prediction})
49
+ except Exception as e:
50
+ return json.dumps({'error': str(e)}), 500 # Internal Server Error
51
+ else:
52
+ return json.dumps({'error': 'Missing "image_url" in request body'}), 400 # Bad Request
53
+ else:
54
+ return json.dumps({'error': 'Only POST requests are allowed'}), 405 # Method Not Allowed
55
+
56
+ st.experimental_next_router(api_endpoint) # Register the API endpoint
57
+
58
+ if image_url_ui:
59
  try:
60
+ # Load image from UI input (if URL is provided)
61
+ response = requests.get(image_url_ui)
62
  image = Image.open(BytesIO(response.content))
63
  st.image(image, caption='Image from URL', use_column_width=True)
64
  st.write("")
65
  st.write("Classifying...")
66
 
67
+ # Predict and display result (for UI)
68
  prediction = predict_image(image)
69
  st.write(f"Predicted Class: {prediction}")
70
  except Exception as e:
71
  st.write(f"Error: {e}")
72
 
73
+ # Display API endpoint information
74
+ space_url = st.session_state.get('huggingface_space_url') # Assuming it's available
75
+ if space_url:
76
+ api_endpoint_url = f"{space_url}/api/classify" # Construct the URL based on Space URL
77
+ st.write(f"You can also use this API endpoint to classify images:")
78
+ st.write(f"```curl")
79
+ st.write(f"curl -X POST -H 'Content-Type: application/json' -d '{{ \"image_url\": \"https://example.jpg\" }}' {api_endpoint_url}")
80
+ st.write(f"```")
81
+ st.write(f"This will return the predicted class in JSON format.")