rkihacker commited on
Commit
6f48975
Β·
verified Β·
1 Parent(s): 00ec3d3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +28 -28
app.py CHANGED
@@ -9,6 +9,7 @@ import base64
9
  import os
10
  import json
11
  import logging
 
12
 
13
  import gradio as gr
14
  import httpx
@@ -73,25 +74,13 @@ def moderate_content(text_input, image_input, video_input, audio_input, language
73
  return "Please provide at least one input (text, image, video, or audio).", None
74
 
75
  logging.info("Preparing payload for moderation API...")
76
- payload = {
77
- "model": "nai-moderation-latest" # This is the model name expected by our API
78
- }
79
-
80
- if text_input:
81
- payload["input"] = text_input
82
-
83
- image_b64 = file_to_base64(image_input)
84
- if image_b64:
85
- payload["image"] = image_b64
86
-
87
- video_b64 = file_to_base64(video_input)
88
- if video_b64:
89
- payload["video"] = video_b64
90
-
91
- audio_b64 = file_to_base64(audio_input)
92
- if audio_b64:
93
  payload["voice"] = audio_b64
94
- language_code = SORTED_LANGUAGES.get(language_full_name, "en") # Default to 'en'
95
  payload["language"] = language_code
96
  logging.info(f"Audio detected. Using language: {language_full_name} ({language_code})")
97
 
@@ -99,14 +88,19 @@ def moderate_content(text_input, image_input, video_input, audio_input, language
99
 
100
  summary_output = "An error occurred. Please check the logs."
101
  full_response_output = {}
 
102
 
103
  try:
104
  with httpx.Client(timeout=180.0) as client:
 
105
  response = client.post(MODERATION_ENDPOINT, json=payload)
106
- response.raise_for_status() # Raises HTTPStatusError for 4xx/5xx responses
 
 
 
107
 
108
  data = response.json()
109
- full_response_output = data
110
 
111
  if not data.get("results"):
112
  summary_output = "API returned an empty result. This might happen if media processing fails (e.g., a video with no frames)."
@@ -121,6 +115,8 @@ def moderate_content(text_input, image_input, video_input, audio_input, language
121
  categories_str = ", ".join(flagged_categories) if flagged_categories else "None"
122
 
123
  summary_output = f"""
 
 
124
  **Moderation Status:** {status}
125
  ---
126
  **Reason:** {reason}
@@ -130,27 +126,29 @@ def moderate_content(text_input, image_input, video_input, audio_input, language
130
  **Transcribed Text (from audio):**
131
  {transcribed}
132
  """
133
- logging.info("Successfully received and parsed moderation response.")
134
 
135
- # --- MODIFIED: Enhanced Error Handling ---
136
  except httpx.HTTPStatusError as e:
137
- # Catches errors returned by the backend API (e.g., 422, 500)
138
  user_message = "The moderation service returned an error."
139
  error_details = ""
 
 
140
  try:
141
- # Try to parse the JSON error response from the server
142
  error_json = e.response.json()
143
  detail = error_json.get("detail", "No specific error detail provided.")
144
  error_details = f"**Reason:** {detail}"
 
145
  full_response_output = {"error": "Backend API Error", "status_code": e.response.status_code, "details": error_json}
146
  except (json.JSONDecodeError, AttributeError):
147
- # Fallback for non-JSON or unexpected error formats
148
  error_details = f"**Raw Server Response:**\n```\n{e.response.text}\n```"
 
149
  full_response_output = {"error": "Backend API Error", "status_code": e.response.status_code, "details": e.response.text}
150
 
151
  summary_output = f"""
152
  **🚫 Error from Moderation Service (HTTP {e.response.status_code})**
153
  ---
 
 
154
  {user_message}
155
 
156
  {error_details}
@@ -158,19 +156,21 @@ def moderate_content(text_input, image_input, video_input, audio_input, language
158
  logging.error(f"HTTP Status Error: {e.response.status_code} - Response: {e.response.text}")
159
 
160
  except httpx.RequestError as e:
161
- # Catches network errors (e.g., server is down, DNS issues)
 
 
162
  summary_output = f"""
163
  **πŸ”Œ Connection Error**
164
  ---
165
- Could not connect to the API server at `{API_BASE_URL}`.
166
 
167
  Please ensure the backend server is running and the URL is configured correctly in your `.env` file.
168
  """
 
169
  full_response_output = {"error": "Connection Error", "url": API_BASE_URL, "details": str(e)}
170
  logging.error(f"Request Error: Could not connect to {API_BASE_URL}. Details: {e}")
171
 
172
  except Exception as e:
173
- # A catch-all for any other unexpected errors in this Gradio script
174
  summary_output = f"""
175
  **πŸ’₯ An Unexpected Application Error Occurred**
176
  ---
 
9
  import os
10
  import json
11
  import logging
12
+ import time
13
 
14
  import gradio as gr
15
  import httpx
 
74
  return "Please provide at least one input (text, image, video, or audio).", None
75
 
76
  logging.info("Preparing payload for moderation API...")
77
+ payload = { "model": "nai-moderation-latest" }
78
+ if text_input: payload["input"] = text_input
79
+ if image_b64 := file_to_base64(image_input): payload["image"] = image_b64
80
+ if video_b64 := file_to_base64(video_input): payload["video"] = video_b64
81
+ if audio_b64 := file_to_base64(audio_input):
 
 
 
 
 
 
 
 
 
 
 
 
82
  payload["voice"] = audio_b64
83
+ language_code = SORTED_LANGUAGES.get(language_full_name, "en")
84
  payload["language"] = language_code
85
  logging.info(f"Audio detected. Using language: {language_full_name} ({language_code})")
86
 
 
88
 
89
  summary_output = "An error occurred. Please check the logs."
90
  full_response_output = {}
91
+ latency_ms = None
92
 
93
  try:
94
  with httpx.Client(timeout=180.0) as client:
95
+ start_time = time.monotonic()
96
  response = client.post(MODERATION_ENDPOINT, json=payload)
97
+ latency_ms = (time.monotonic() - start_time) * 1000
98
+ logging.info(f"API response received in {latency_ms:.2f} ms with status code {response.status_code}")
99
+
100
+ response.raise_for_status()
101
 
102
  data = response.json()
103
+ full_response_output = data # <-- MODIFIED: Assign raw data, without adding latency
104
 
105
  if not data.get("results"):
106
  summary_output = "API returned an empty result. This might happen if media processing fails (e.g., a video with no frames)."
 
115
  categories_str = ", ".join(flagged_categories) if flagged_categories else "None"
116
 
117
  summary_output = f"""
118
+ **API Latency:** {latency_ms:.2f} ms
119
+ ---
120
  **Moderation Status:** {status}
121
  ---
122
  **Reason:** {reason}
 
126
  **Transcribed Text (from audio):**
127
  {transcribed}
128
  """
129
+ logging.info("Successfully parsed moderation response.")
130
 
 
131
  except httpx.HTTPStatusError as e:
 
132
  user_message = "The moderation service returned an error."
133
  error_details = ""
134
+ latency_str = f"**API Latency:** {latency_ms:.2f} ms" if latency_ms is not None else ""
135
+
136
  try:
 
137
  error_json = e.response.json()
138
  detail = error_json.get("detail", "No specific error detail provided.")
139
  error_details = f"**Reason:** {detail}"
140
+ # <-- MODIFIED: Latency removed from this dictionary
141
  full_response_output = {"error": "Backend API Error", "status_code": e.response.status_code, "details": error_json}
142
  except (json.JSONDecodeError, AttributeError):
 
143
  error_details = f"**Raw Server Response:**\n```\n{e.response.text}\n```"
144
+ # <-- MODIFIED: Latency removed from this dictionary
145
  full_response_output = {"error": "Backend API Error", "status_code": e.response.status_code, "details": e.response.text}
146
 
147
  summary_output = f"""
148
  **🚫 Error from Moderation Service (HTTP {e.response.status_code})**
149
  ---
150
+ {latency_str}
151
+
152
  {user_message}
153
 
154
  {error_details}
 
156
  logging.error(f"HTTP Status Error: {e.response.status_code} - Response: {e.response.text}")
157
 
158
  except httpx.RequestError as e:
159
+ if latency_ms is None:
160
+ latency_ms = (time.monotonic() - start_time) * 1000 if 'start_time' in locals() else 0
161
+
162
  summary_output = f"""
163
  **πŸ”Œ Connection Error**
164
  ---
165
+ Could not connect to the API server at `{API_BASE_URL}`. The request failed after {latency_ms:.0f} ms.
166
 
167
  Please ensure the backend server is running and the URL is configured correctly in your `.env` file.
168
  """
169
+ # <-- MODIFIED: Latency removed from this dictionary
170
  full_response_output = {"error": "Connection Error", "url": API_BASE_URL, "details": str(e)}
171
  logging.error(f"Request Error: Could not connect to {API_BASE_URL}. Details: {e}")
172
 
173
  except Exception as e:
 
174
  summary_output = f"""
175
  **πŸ’₯ An Unexpected Application Error Occurred**
176
  ---