AliA1997 commited on
Commit
29c07d6
·
1 Parent(s): ad69acc

Completed most of the nsfw classifyer

Browse files
.idea/.gitignore ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ # Default ignored files
2
+ /shelf/
3
+ /workspace.xml
4
+ # Editor-based HTTP Client requests
5
+ /httpRequests/
6
+ # Datasource local storage ignored files
7
+ /dataSources/
8
+ /dataSources.local.xml
.idea/NSFW-Checker.iml ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <module type="PYTHON_MODULE" version="4">
3
+ <component name="NewModuleRootManager">
4
+ <content url="file://$MODULE_DIR$" />
5
+ <orderEntry type="jdk" jdkName="Python 3.13" jdkType="Python SDK" />
6
+ <orderEntry type="sourceFolder" forTests="false" />
7
+ </component>
8
+ <component name="PyDocumentationSettings">
9
+ <option name="format" value="PLAIN" />
10
+ <option name="myDocStringFormat" value="Plain" />
11
+ </component>
12
+ </module>
.idea/inspectionProfiles/profiles_settings.xml ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ <component name="InspectionProjectProfileManager">
2
+ <settings>
3
+ <option name="USE_PROJECT_PROFILE" value="false" />
4
+ <version value="1.0" />
5
+ </settings>
6
+ </component>
.idea/misc.xml ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="Black">
4
+ <option name="sdkName" value="Python 3.13" />
5
+ </component>
6
+ <component name="ProjectRootManager" version="2" project-jdk-name="Python 3.13" project-jdk-type="Python SDK" />
7
+ </project>
.idea/modules.xml ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="ProjectModuleManager">
4
+ <modules>
5
+ <module fileurl="file://$PROJECT_DIR$/.idea/NSFW-Checker.iml" filepath="$PROJECT_DIR$/.idea/NSFW-Checker.iml" />
6
+ </modules>
7
+ </component>
8
+ </project>
.idea/vcs.xml ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="VcsDirectoryMappings">
4
+ <mapping directory="" vcs="Git" />
5
+ </component>
6
+ </project>
app.py CHANGED
@@ -1,70 +1,60 @@
 
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
 
3
 
 
4
 
5
- def respond(
6
- message,
7
- history: list[dict[str, str]],
8
- system_message,
9
- max_tokens,
10
- temperature,
11
- top_p,
12
- hf_token: gr.OAuthToken,
13
- ):
14
- """
15
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
16
- """
17
- client = InferenceClient(token=hf_token.token, model="openai/gpt-oss-20b")
18
 
19
- messages = [{"role": "system", "content": system_message}]
 
 
 
 
 
20
 
21
- messages.extend(history)
22
 
23
- messages.append({"role": "user", "content": message})
 
24
 
25
- response = ""
26
 
27
- for message in client.chat_completion(
28
- messages,
29
- max_tokens=max_tokens,
30
- stream=True,
31
- temperature=temperature,
32
- top_p=top_p,
33
- ):
34
- choices = message.choices
35
- token = ""
36
- if len(choices) and choices[0].delta.content:
37
- token = choices[0].delta.content
38
 
39
- response += token
40
- yield response
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
 
42
 
43
  """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
  """
 
 
 
46
  chatbot = gr.ChatInterface(
47
  respond,
48
  type="messages",
49
- additional_inputs=[
50
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
51
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
52
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
53
- gr.Slider(
54
- minimum=0.1,
55
- maximum=1.0,
56
- value=0.95,
57
- step=0.05,
58
- label="Top-p (nucleus sampling)",
59
- ),
60
- ],
61
  )
62
 
63
  with gr.Blocks() as demo:
64
- with gr.Sidebar():
65
- gr.LoginButton()
66
  chatbot.render()
67
 
68
-
69
  if __name__ == "__main__":
70
  demo.launch()
 
1
+ import os
2
+ from json import dumps
3
  import gradio as gr
4
+ from huggingface_hub import login
5
+ from transformers import pipeline
6
 
7
+ from classify_utils import classify_image_if_nsfw, get_nsfw_classifier, get_normal_classifier
8
 
9
+ global classifier
 
 
 
 
 
 
 
 
 
 
 
 
10
 
11
+ def init_login():
12
+ try:
13
+ login(os.environ.get('HF_TOKEN'))
14
+ print("logged in successfully")
15
+ except Exception as e:
16
+ print("issue logging into hugging face:", e)
17
 
 
18
 
19
+ def init_classifier():
20
+ classifier = pipeline("image-classification", model="Falconsai/nsfw_image_detection")
21
 
 
22
 
 
 
 
 
 
 
 
 
 
 
 
23
 
24
+ def respond(
25
+ message,
26
+ history: list[dict[str, str]],
27
+ ):
28
+ json_response = classify_image_if_nsfw(classifier, message)
29
+ print(dumps(json_response, indent=4))
30
+ normal_classifier = get_normal_classifier(json_response)
31
+ nsfw_classifier = get_nsfw_classifier(json_response)
32
+ # Fixed: Use 'and' instead of '&&', and improved logic flow
33
+ if nsfw_classifier is not None and nsfw_classifier['score'] > 0.75:
34
+ return {"text": "Very Explicit"}
35
+ elif nsfw_classifier is not None and nsfw_classifier['score'] > 0.5:
36
+ return {"text": "Somewhat Explicit"}
37
+ elif normal_classifier is not None and normal_classifier['score'] < 0.8:
38
+ return {"text": "Somewhat Normal"}
39
+ else:
40
+ return {"text": "Normal"}
41
+
42
 
43
 
44
  """
45
+ Functionality of nsfw detector
46
  """
47
+ init_login()
48
+ init_classifier()
49
+
50
  chatbot = gr.ChatInterface(
51
  respond,
52
  type="messages",
53
+ additional_inputs=[]
 
 
 
 
 
 
 
 
 
 
 
54
  )
55
 
56
  with gr.Blocks() as demo:
 
 
57
  chatbot.render()
58
 
 
59
  if __name__ == "__main__":
60
  demo.launch()
classify_utils.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import requests
3
+ import base64
4
+ from PIL import Image
5
+ from io import BytesIO
6
+ from transformers import ImageClassificationPipeline
7
+
8
+
9
+ def get_normal_classifier(items: list[object])->object | None:
10
+ normal_classifier = next((item for item in items if item["label"] == "normal"), None)
11
+ return normal_classifier
12
+
13
+ def get_nsfw_classifier(items: list[object])->object | None:
14
+ nsfw_classifier = next((item for item in items if item["label"] == "nsfw"), None)
15
+ return nsfw_classifier
16
+
17
+
18
+ def classify_image_if_nsfw(classifier: ImageClassificationPipeline, image_url: str):
19
+ try:
20
+ # Check if it's a base64 data URL
21
+ if image_url.startswith('data:image'):
22
+ print("Processing base64 data URL")
23
+
24
+ # Extract the base64 data from the data URL
25
+ match = re.match(r'data:image/(?P<ext>\w+);base64,(?P<data>.*)', image_url)
26
+ if not match:
27
+ raise ValueError("Invalid base64 data URL format")
28
+
29
+ base64_data = match.group('data')
30
+ image_format = match.group('ext')
31
+
32
+ # Decode the base64 data
33
+ image_data = base64.b64decode(base64_data)
34
+
35
+ # Open the image from decoded data
36
+ img = Image.open(BytesIO(image_data))
37
+
38
+ else:
39
+ # It's a regular URL - download the image
40
+ print("Processing regular URL")
41
+ response = requests.get(image_url)
42
+ response.raise_for_status()
43
+
44
+ # Open and process the image
45
+ img = Image.open(BytesIO(response.content))
46
+
47
+ print("Image size:", img.size)
48
+ print("Image format:", img.format)
49
+ print("Image mode:", img.mode)
50
+
51
+ # Ensure image is in RGB mode (required by most models)
52
+ if img.mode != 'RGB':
53
+ img = img.convert('RGB')
54
+
55
+ # Classify the image
56
+ classifier_response = classifier(img)
57
+ print("Classifier Response:", classifier_response)
58
+ normal_classifier = classifier_response
59
+ return classifier_response
60
+
61
+ except Exception as e:
62
+ print(f"Error processing image: {e}")
63
+ raise
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ gradio~=5.49.1
2
+ gradio[oauth]
3
+ requests~=2.32.4
4
+ huggingface-hub~=0.36.0
5
+ pillow~=11.3.0
6
+ transformers~=4.53.2
7
+ base64