kkAsmaa commited on
Commit
85bf665
ยท
verified ยท
1 Parent(s): 84bb3ad

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +29 -17
app.py CHANGED
@@ -4,28 +4,33 @@ import os
4
  import torch
5
  import uvicorn
6
  import json
 
7
  from fastapi import FastAPI
8
  from pydantic import BaseModel
9
  from transformers import BertTokenizer, AutoModelForSequenceClassification
10
  from arabert.preprocess import ArabertPreprocessor
11
- from tabulate import tabulate # ู…ูƒุชุจุฉ ูุฎู…ุฉ ู„ุจู†ุงุก ุฌุฏุงูˆู„ ู…ู†ุณู‚ุฉ ููŠ ุงู„ู„ูˆุบุฒ ุงู„ุณุญุงุจูŠุฉ
 
12
 
13
  MODEL_REPO = "kkAsmaa/ChildShield"
14
  MODEL_NAME = "aubmindlab/bert-base-arabertv02-twitter"
15
  SUB_FOLDER = "ChildShield"
16
  HF_TOKEN = os.getenv("HF_TOKEN")
17
 
 
18
  print("๐Ÿ”„ Loading ChildShield Model Weights with Deep Window Auto-Logging Features...")
19
  tokenizer = BertTokenizer.from_pretrained(MODEL_NAME)
20
  model = AutoModelForSequenceClassification.from_pretrained(MODEL_REPO, token=HF_TOKEN, subfolder=SUB_FOLDER)
21
  model.eval()
22
  arabic_prep = ArabertPreprocessor(model_name=MODEL_NAME)
23
 
 
24
  app = FastAPI(title="ChildShield Backend API")
25
 
26
  class InputData(BaseModel):
27
  text: str
28
 
 
29
  def clean_obfuscation(text):
30
  text = str(text)
31
  text = re.sub(r'https?://\S+|www\.\S+|@\S+|#', '', text)
@@ -39,9 +44,10 @@ def clean_obfuscation(text):
39
 
40
  def full_preprocess(text):
41
  text_no_trickery = clean_obfuscation(text)
42
- final_text = arabic_prep.preprocess(text_no_trickery)
43
  return final_text
44
 
 
45
  def predict_safety_api(text):
46
  """
47
  Arabic text classification gateway utilizing a custom sliding window configuration with 20 token overlap.
@@ -72,7 +78,7 @@ def predict_safety_api(text):
72
  highest_safe_prob = 0.0
73
  windows_analysis = []
74
  triggered_windows = []
75
- windows_table_data = [] # ู…ุตููˆูุฉ ู„ุชุฌู‡ูŠุฒ ุงู„ุฌุฏูˆู„ ุงู„ู†ุตูŠ ููŠ ุงู„ู„ูˆุบุฒ
76
 
77
  for idx, win_ids in enumerate(windows):
78
  window_text = tokenizer.decode(win_ids, skip_special_tokens=True)
@@ -83,6 +89,7 @@ def predict_safety_api(text):
83
  padding="max_length",
84
  max_length=60
85
  )
 
86
  with torch.no_grad():
87
  outputs = model(**inputs)
88
  probs = torch.softmax(outputs.logits, dim=-1).flatten().tolist()
@@ -99,13 +106,13 @@ def predict_safety_api(text):
99
  "prediction": prediction
100
  })
101
 
102
- # ุชุฌู‡ูŠุฒ ุฃุณุทุฑ ุงู„ุฌุฏูˆู„ ุงู„ู†ุตูŠ ุงู„ูุฎู… ู„ู…ุญุงูƒุงุฉ ู…ุฎุฑุฌุงุช ุงู„ูƒูˆู†ุณูˆู„ ุงู„ู…ุทูˆุฑ
103
  windows_table_data.append([
104
  f"Win {idx + 1}",
105
  window_text[:45] + "..." if len(window_text) > 45 else window_text,
106
  f"{safe_prob * 100:.2f}%",
107
  f"{unsafe_prob * 100:.2f}%",
108
- f"โŒ {prediction}" if prediction == "UNSAFE" else f"๐Ÿ {prediction}"
109
  ])
110
 
111
  if unsafe_prob > 0.50:
@@ -123,30 +130,33 @@ def predict_safety_api(text):
123
  safe_confidence_score = round(1.0 - highest_unsafe_prob, 4)
124
  final_confidence = unsafe_confidence_score if is_blocked else safe_confidence_score
125
 
126
- # ๐Ÿ”ฅ ู†ู‚ู„ ูƒุงู…ู„ ู…ุฎุฑุฌุงุช ุงู„ูƒูˆู†ุณูˆู„ ุงู„ู…ู„ูˆู†ุฉ ูˆุงู„ู…ู†ุธู…ุฉ ู„ุชุทุจุน ุญูŠุงู‹ ุฏุงุฎู„ ุดุงุดุฉ ุงู„ู€ Logs ุงู„ุณูˆุฏุงุก
127
- alert_banner = "๐Ÿšจ [BLOCK] CHILDSHIELD AI INFERENCE REPORT" if is_blocked else "๐Ÿ [PASS] CHILDSHIELD AI INFERENCE REPORT"
128
  print(f"\n================ {alert_banner} ================")
129
- print(f"๐Ÿ“ฅ Received Original Text:\n\"{text.strip()}\"")
130
- print(f"\n๐Ÿงน Preprocessed Cleaned Text:\n\"{cleaned_text}\"")
131
- print(f"\n๐Ÿ”‘ Total Page Tokens Count : {total_tokens_count}")
132
- print(f"๐ŸชŸ Total Sliding Windows Run : {total_windows_count} Windows (Size: 60, Overlap: 20)")
133
- print(f"๐ŸŽฏ Final Security Verdict : {final_prediction}")
134
- print(f"๐Ÿ† Model Decision Confidence : {formatted_confidence}")
135
- print(f"๐Ÿ›‘ Triggered Windows ID : {triggered_windows}")
136
- print("\n๐Ÿ“Š --- Windows Detailed Semantic Analysis Table ---")
137
  print(tabulate(windows_table_data, headers=["ID", "Window Text Preview", "Safe Prob", "Unsafe Prob", "Verdict"], tablefmt="grid"))
138
  print("========================================================================\n")
139
 
140
- # ๐ŸŽฏ ุงู„ุชุญุฏูŠุซ ุงู„ุชูˆุณุนูŠ ุงู„ุนู…ูŠู‚: ุชุฎุฒูŠู† ูˆุญูุธ ุงู„ู†ุตูˆุต ูˆุงู„ู†ูˆุงูุฐ ูˆุงู„ู†ุณุจ ุงู„ู…ุฆูˆูŠุฉ ูƒุงู…ู„ุฉ ู„ู„ู…ุณุชู‚ุจู„
141
  try:
142
  log_file_path = "production_logs.txt"
143
- # ุชุญูˆูŠู„ ู…ุตููˆูุฉ ุงู„ู†ูˆุงูุฐ ูƒุงู…ู„ุฉ ู„ู†ุต ุฌูŠุณูˆู† ู…ุถุบูˆุท ููŠ ุณุทุฑ ูˆุงุญุฏ
144
  windows_json_blob = json.dumps(windows_analysis, ensure_ascii=False)
145
  with open(log_file_path, "a", encoding="utf-8") as log_file:
146
  log_file.write(f"Verdict: {final_prediction} | Confidence: {formatted_confidence} | Tokens: {total_tokens_count} | Windows: {total_windows_count} | Text: {text.strip()} | DeepAnalysis: {windows_json_blob}\n")
 
 
147
  except Exception as e:
148
  print(f"โš ๏ธ [Logging Warning] Could not write to log file: {e}")
149
 
 
150
  return {
151
  "original_text": text,
152
  "cleaned_text": cleaned_text,
@@ -162,11 +172,13 @@ def predict_safety_api(text):
162
  "confidence": formatted_confidence
163
  }
164
 
 
165
  @app.post("/predict")
166
  def predict(data: InputData):
167
  result = predict_safety_api(data.text)
168
  return result
169
 
 
170
  gradio_interface = gr.Interface(
171
  fn=predict_safety_api,
172
  inputs=gr.Textbox(lines=4, placeholder="Enter Arabic text to analyze..."),
 
4
  import torch
5
  import uvicorn
6
  import json
7
+
8
  from fastapi import FastAPI
9
  from pydantic import BaseModel
10
  from transformers import BertTokenizer, AutoModelForSequenceClassification
11
  from arabert.preprocess import ArabertPreprocessor
12
+ from tabulate import tabulate
13
+
14
 
15
  MODEL_REPO = "kkAsmaa/ChildShield"
16
  MODEL_NAME = "aubmindlab/bert-base-arabertv02-twitter"
17
  SUB_FOLDER = "ChildShield"
18
  HF_TOKEN = os.getenv("HF_TOKEN")
19
 
20
+
21
  print("๐Ÿ”„ Loading ChildShield Model Weights with Deep Window Auto-Logging Features...")
22
  tokenizer = BertTokenizer.from_pretrained(MODEL_NAME)
23
  model = AutoModelForSequenceClassification.from_pretrained(MODEL_REPO, token=HF_TOKEN, subfolder=SUB_FOLDER)
24
  model.eval()
25
  arabic_prep = ArabertPreprocessor(model_name=MODEL_NAME)
26
 
27
+
28
  app = FastAPI(title="ChildShield Backend API")
29
 
30
  class InputData(BaseModel):
31
  text: str
32
 
33
+
34
  def clean_obfuscation(text):
35
  text = str(text)
36
  text = re.sub(r'https?://\S+|www\.\S+|@\S+|#', '', text)
 
44
 
45
  def full_preprocess(text):
46
  text_no_trickery = clean_obfuscation(text)
47
+ final_text = arabic_prep.preprocess(text_no_trickery)
48
  return final_text
49
 
50
+
51
  def predict_safety_api(text):
52
  """
53
  Arabic text classification gateway utilizing a custom sliding window configuration with 20 token overlap.
 
78
  highest_safe_prob = 0.0
79
  windows_analysis = []
80
  triggered_windows = []
81
+ windows_table_data = []
82
 
83
  for idx, win_ids in enumerate(windows):
84
  window_text = tokenizer.decode(win_ids, skip_special_tokens=True)
 
89
  padding="max_length",
90
  max_length=60
91
  )
92
+
93
  with torch.no_grad():
94
  outputs = model(**inputs)
95
  probs = torch.softmax(outputs.logits, dim=-1).flatten().tolist()
 
106
  "prediction": prediction
107
  })
108
 
109
+
110
  windows_table_data.append([
111
  f"Win {idx + 1}",
112
  window_text[:45] + "..." if len(window_text) > 45 else window_text,
113
  f"{safe_prob * 100:.2f}%",
114
  f"{unsafe_prob * 100:.2f}%",
115
+ f"โŒ {prediction}" if prediction == "UNSAFE" else f"โœ… {prediction}"
116
  ])
117
 
118
  if unsafe_prob > 0.50:
 
130
  safe_confidence_score = round(1.0 - highest_unsafe_prob, 4)
131
  final_confidence = unsafe_confidence_score if is_blocked else safe_confidence_score
132
 
133
+
134
+ alert_banner = "๐Ÿšจ [BLOCK] CHILDSHIELD AI INFERENCE REPORT" if is_blocked else "โœ… [PASS] CHILDSHIELD AI INFERENCE REPORT"
135
  print(f"\n================ {alert_banner} ================")
136
+ print(f" Received Original Text:\n\"{text.strip()}\"")
137
+ print(f"\n Preprocessed Cleaned Text:\n\"{cleaned_text}\"")
138
+ print(f"\n Total Page Tokens Count : {total_tokens_count}")
139
+ print(f" Total Sliding Windows Run : {total_windows_count} Windows (Size: 60, Overlap: 20)")
140
+ print(f" Final Security Verdict : {final_prediction}")
141
+ print(f" Model Decision Confidence : {formatted_confidence}")
142
+ print(f" Triggered Windows ID : {triggered_windows}")
143
+ print("\n --- Windows Detailed Semantic Analysis Table ---")
144
  print(tabulate(windows_table_data, headers=["ID", "Window Text Preview", "Safe Prob", "Unsafe Prob", "Verdict"], tablefmt="grid"))
145
  print("========================================================================\n")
146
 
147
+
148
  try:
149
  log_file_path = "production_logs.txt"
150
+
151
  windows_json_blob = json.dumps(windows_analysis, ensure_ascii=False)
152
  with open(log_file_path, "a", encoding="utf-8") as log_file:
153
  log_file.write(f"Verdict: {final_prediction} | Confidence: {formatted_confidence} | Tokens: {total_tokens_count} | Windows: {total_windows_count} | Text: {text.strip()} | DeepAnalysis: {windows_json_blob}\n")
154
+
155
+
156
  except Exception as e:
157
  print(f"โš ๏ธ [Logging Warning] Could not write to log file: {e}")
158
 
159
+
160
  return {
161
  "original_text": text,
162
  "cleaned_text": cleaned_text,
 
172
  "confidence": formatted_confidence
173
  }
174
 
175
+
176
  @app.post("/predict")
177
  def predict(data: InputData):
178
  result = predict_safety_api(data.text)
179
  return result
180
 
181
+
182
  gradio_interface = gr.Interface(
183
  fn=predict_safety_api,
184
  inputs=gr.Textbox(lines=4, placeholder="Enter Arabic text to analyze..."),