nivashuggingface commited on
Commit
4b0c1ef
1 Parent(s): b76e69f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +16 -62
app.py CHANGED
@@ -5,75 +5,28 @@ import numpy as np
5
  import io
6
  from PIL import Image
7
  import base64
8
- import os
9
- import requests
10
- from tenacity import retry, wait_exponential, stop_after_attempt
11
 
12
- # Load Hugging Face token from environment variable
13
- HF_TOKEN = os.getenv("HF_TOKEN")
14
- if not HF_TOKEN:
15
- raise ValueError("Hugging Face token not found in environment variables.")
16
 
17
- @retry(wait=wait_exponential(multiplier=1, min=4, max=10), stop=stop_after_attempt(5))
18
- def get_dynamic_endpoint():
19
- """
20
- Fetch the dynamic endpoint using the Hugging Face API.
21
- Returns:
22
- str: The current dynamic endpoint.
23
- """
24
- api_url = "https://api.huggingface.co/space/duchaba/friendly-text-moderation"
25
- headers = {"Authorization": f"Bearer {HF_TOKEN}"}
26
-
27
- response = requests.get(api_url, headers=headers)
28
- response.raise_for_status() # Raise an error for bad status codes
29
-
30
- # Extract the endpoint from the response
31
- data = response.json()
32
- endpoint = data.get("url")
33
- if not endpoint:
34
- raise ValueError("Endpoint URL not found in the response.")
35
- return endpoint
36
 
37
  def moderate_text(text, safer_value):
38
- """
39
- Moderate the given text using the Hugging Face API.
40
-
41
- Args:
42
- text (str): The text to be moderated.
43
- safer_value (float): The safer value to be used for moderation.
44
-
45
- Returns:
46
- tuple: A tuple containing the moderation result and the generated image.
47
- """
48
- try:
49
- # Fetch the dynamic endpoint
50
- dynamic_endpoint = get_dynamic_endpoint()
51
-
52
- # Initialize the client with the dynamic endpoint
53
- client = Client(dynamic_endpoint, hf_token=HF_TOKEN)
54
- result = client.predict(
55
- text,
56
- safer_value,
57
- api_name="/censor_me"
58
- )
59
 
60
- # Ensure the result contains the expected data
61
- base64_data = result.get('plot', '').split(',')[1] if 'plot' in result else None
62
- if not base64_data:
63
- raise ValueError("Expected plot data not found in the result.")
64
 
65
- # Decode base64 to bytes
66
- img_data = base64.b64decode(base64_data)
67
 
68
- # Convert bytes to PIL Image
69
- img = Image.open(io.BytesIO(img_data))
70
 
71
- return result, img
72
-
73
- except Exception as e:
74
- # Log the error for debugging purposes
75
- print(f"Error occurred: {e}")
76
- return str(e), None
77
 
78
  # Define the Gradio interface
79
  demo = gr.Interface(
@@ -84,7 +37,8 @@ demo = gr.Interface(
84
  ],
85
  outputs=[gr.Textbox(label="Moderated Text:", lines=5), gr.Image(type="pil", label="Moderation Pie Chart")],
86
  title="Friendly Text Moderator",
87
- description="Enter text to be moderated and adjust the safer value to see how it affects the moderation."
 
88
  )
89
 
90
  # Customize the CSS
 
5
  import io
6
  from PIL import Image
7
  import base64
 
 
 
8
 
9
+ #client = Client("https://duchaba-friendly-text-moderation.hf.space/--replicas/gffry/")
10
+ client = Client("https://duchaba-friendly-text-moderation.hf.space/--replicas/6rx2j/")
 
 
11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
 
13
  def moderate_text(text, safer_value):
14
+ result = client.predict(
15
+ text,
16
+ safer_value,
17
+ api_name="/censor_me"
18
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
+ # Example structure of the result
21
+ base64_data = result.get('plot', '').split(',')[1]
 
 
22
 
23
+ # Decode base64 to bytes
24
+ img_data = base64.b64decode(base64_data)
25
 
26
+ # Convert bytes to PIL Image
27
+ img = Image.open(io.BytesIO(img_data))
28
 
29
+ return result, img
 
 
 
 
 
30
 
31
  # Define the Gradio interface
32
  demo = gr.Interface(
 
37
  ],
38
  outputs=[gr.Textbox(label="Moderated Text:", lines=5), gr.Image(type="pil", label="Moderation Pie Chart")],
39
  title="Friendly Text Moderator",
40
+ description="Enter text to be moderated and adjust the safer value to see how it affects the moderation.",
41
+ theme="compact"
42
  )
43
 
44
  # Customize the CSS