nyasukun commited on
Commit
5df8f2d
·
1 Parent(s): 8936e3e
Files changed (4) hide show
  1. .gitignore +60 -0
  2. README.md +66 -1
  3. app.py +361 -59
  4. requirements.txt +7 -1
.gitignore ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Environment variables
2
+ .env
3
+
4
+ # Pipenv files
5
+ Pipfile
6
+ Pipfile.lock
7
+
8
+ # Python
9
+ __pycache__/
10
+ *.py[cod]
11
+ *$py.class
12
+ *.so
13
+ .Python
14
+ build/
15
+ develop-eggs/
16
+ dist/
17
+ downloads/
18
+ eggs/
19
+ .eggs/
20
+ lib/
21
+ lib64/
22
+ parts/
23
+ sdist/
24
+ var/
25
+ wheels/
26
+ *.egg-info/
27
+ .installed.cfg
28
+ *.egg
29
+
30
+ # Virtual Environment
31
+ .env
32
+ .venv
33
+ env/
34
+ venv/
35
+ ENV/
36
+ env.bak/
37
+ venv.bak/
38
+
39
+ # IDE
40
+ .idea/
41
+ .vscode/
42
+ *.swp
43
+ *.swo
44
+ .DS_Store
45
+
46
+ # Jupyter Notebook
47
+ .ipynb_checkpoints
48
+
49
+ # Model files and cache
50
+ *.pt
51
+ *.pth
52
+ *.bin
53
+ .cache/
54
+ *.ckpt
55
+ transformers_cache/
56
+ torch_cache/
57
+
58
+ # Logs
59
+ *.log
60
+ logs/
README.md CHANGED
@@ -9,4 +9,69 @@ app_file: app.py
9
  pinned: false
10
  ---
11
 
12
- An example chatbot using [Gradio](https://gradio.app), [`huggingface_hub`](https://huggingface.co/docs/huggingface_hub/v0.22.2/en/index), and the [Hugging Face Inference API](https://huggingface.co/docs/api-inference/index).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  pinned: false
10
  ---
11
 
12
+ # Toxic Total: Multi-Model Toxicity Evaluation Platform
13
+
14
+ ## Overview
15
+ Toxic Total is a comprehensive platform that evaluates text toxicity using multiple language models and classifiers. This platform provides a unique approach by combining both generative and classification models to analyze potentially toxic content.
16
+
17
+ ## Features
18
+
19
+ ### 1. Text Generation Models
20
+ Our platform utilizes four state-of-the-art language models:
21
+ - **Zephyr-7B**: Specialized in understanding context and nuance
22
+ - **Llama-2**: Known for its robust performance in content analysis
23
+ - **Mistral-7B**: Offers precise and detailed text evaluation
24
+ - **Claude-2**: Provides comprehensive toxicity assessment
25
+
26
+ ### 2. Classification Models
27
+ We employ four specialized classification models:
28
+ - **Toxic-BERT**: Fine-tuned for toxic content detection
29
+ - **RoBERTa-Toxic**: Advanced toxic pattern recognition
30
+ - **DistilBERT-Toxic**: Efficient toxicity classification
31
+ - **XLM-RoBERTa-Toxic**: Multilingual toxicity detection
32
+
33
+ ### 3. Community Integration
34
+ Access to community insights and discussions about similar content patterns and toxicity analysis.
35
+
36
+ ## Technical Details
37
+
38
+ ### Model Architecture
39
+ Each model in our platform is carefully selected to provide complementary analysis:
40
+ ```python
41
+ def analyze_toxicity(text):
42
+ # Multiple model evaluation
43
+ llm_results = text_generation_models(text)
44
+ classification_results = toxicity_classifiers(text)
45
+ community_insights = fetch_community_data(text)
46
+ return combined_analysis(llm_results, classification_results, community_insights)
47
+ ```
48
+
49
+ ### Performance Considerations
50
+ - Real-time analysis capabilities
51
+ - Efficient multi-model parallel processing
52
+ - Optimized response generation
53
+
54
+ ## Usage Guidelines
55
+
56
+ 1. Enter the text you want to analyze in the input box
57
+ 2. Review results from multiple models
58
+ 3. Compare different model perspectives
59
+ 4. Check community insights for context
60
+
61
+ ## References
62
+
63
+ - [Hugging Face Models](https://huggingface.co/models)
64
+ - [Toxicity Classification Research](https://arxiv.org/abs/2103.00153)
65
+ - [Language Model Evaluation Methods](https://arxiv.org/abs/2009.07118)
66
+
67
+ ## Citation
68
+
69
+ If you use this platform in your research, please cite:
70
+ ```bibtex
71
+ @software{toxic_total,
72
+ title = {Toxic Total: Multi-Model Toxicity Evaluation Platform},
73
+ year = {2024},
74
+ publisher = {Hugging Face},
75
+ url = {https://huggingface.co/spaces/[your-username]/toxic-total}
76
+ }
77
+ ```
app.py CHANGED
@@ -1,64 +1,366 @@
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
- """
5
- 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
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
-
9
-
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
-
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
-
26
- messages.append({"role": "user", "content": message})
27
-
28
- response = ""
29
-
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.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
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
  )
 
61
 
 
 
 
 
62
 
63
- if __name__ == "__main__":
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
  demo.launch()
 
 
 
 
1
  import gradio as gr
2
+ from huggingface_hub import AsyncInferenceClient
3
+ from typing import List, Dict, Optional, Union
4
+ import logging
5
+ from dataclasses import dataclass
6
+ from enum import Enum, auto
7
+ import torch
8
+ from transformers import AutoTokenizer, AutoModelForCausalLM, AutoModelForSequenceClassification, pipeline
9
+ import spaces
10
+
11
+ # ロガーの設定
12
+ logging.basicConfig(
13
+ level=logging.INFO,
14
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  )
16
+ logger = logging.getLogger(__name__)
17
 
18
+ # モデルの型定義
19
+ class ModelType(Enum):
20
+ LOCAL = "local"
21
+ INFERENCE_API = "inference_api"
22
 
23
+ @dataclass
24
+ class ModelConfig:
25
+ name: str
26
+ description: str
27
+ type: ModelType
28
+ model_id: Optional[str] = None
29
+ model_path: Optional[str] = None
30
+
31
+ # モデル定義を拡充
32
+ TEXT_GENERATION_MODELS = [
33
+ ModelConfig(
34
+ name="Zephyr-7B",
35
+ description="Specialized in understanding context and nuance",
36
+ type=ModelType.INFERENCE_API,
37
+ model_id="HuggingFaceH4/zephyr-7b-beta"
38
+ ),
39
+ ModelConfig(
40
+ name="Llama-2",
41
+ description="Known for its robust performance in content analysis",
42
+ type=ModelType.LOCAL,
43
+ model_path="meta-llama/Llama-2-7b-hf"
44
+ ),
45
+ ModelConfig(
46
+ name="Mistral-7B",
47
+ description="Offers precise and detailed text evaluation",
48
+ type=ModelType.LOCAL,
49
+ model_path="mistralai/Mistral-7B-v0.1"
50
+ ),
51
+ ModelConfig(
52
+ name="Claude-2",
53
+ description="Provides comprehensive toxicity assessment",
54
+ type=ModelType.INFERENCE_API,
55
+ model_id="anthropic/claude-2"
56
+ )
57
+ ]
58
+
59
+ CLASSIFICATION_MODELS = [
60
+ ModelConfig(
61
+ name="Toxic-BERT",
62
+ description="Fine-tuned for toxic content detection",
63
+ type=ModelType.LOCAL,
64
+ model_path="unitary/toxic-bert"
65
+ ),
66
+ ModelConfig(
67
+ name="RoBERTa-Toxic",
68
+ description="Advanced toxic pattern recognition",
69
+ type=ModelType.INFERENCE_API,
70
+ model_id="unitary/multilingual-toxic-xlm-roberta"
71
+ ),
72
+ ModelConfig(
73
+ name="DistilBERT-Toxic",
74
+ description="Efficient toxicity classification",
75
+ type=ModelType.LOCAL,
76
+ model_path="unitary/multilingual-toxic-distilbert"
77
+ ),
78
+ ModelConfig(
79
+ name="XLM-RoBERTa-Toxic",
80
+ description="Multilingual toxicity detection",
81
+ type=ModelType.INFERENCE_API,
82
+ model_id="unitary/multilingual-toxic-xlm-roberta"
83
+ )
84
+ ]
85
+
86
+ class LocalModelManager:
87
+ def __init__(self):
88
+ self.device = "cuda" if torch.cuda.is_available() else "cpu"
89
+ logger.info(f"Using device: {self.device}")
90
+ self.models = {}
91
+ self.tokenizers = {}
92
+ self.pipelines = {}
93
+
94
+ async def load_model(self, model_path: str, task: str = "text-generation"):
95
+ """モデルの遅延ロード"""
96
+ if model_path not in self.models:
97
+ logger.info(f"Loading model: {model_path}")
98
+ try:
99
+ self.tokenizers[model_path] = AutoTokenizer.from_pretrained(model_path)
100
+
101
+ if task == "text-generation":
102
+ model = AutoModelForCausalLM.from_pretrained(
103
+ model_path,
104
+ torch_dtype=torch.float16,
105
+ device_map="auto"
106
+ )
107
+ self.pipelines[model_path] = pipeline(
108
+ "text-generation",
109
+ model=model,
110
+ tokenizer=self.tokenizers[model_path]
111
+ )
112
+ else: # classification
113
+ model = AutoModelForSequenceClassification.from_pretrained(
114
+ model_path,
115
+ device_map="auto"
116
+ )
117
+ self.pipelines[model_path] = pipeline(
118
+ "text-classification",
119
+ model=model,
120
+ tokenizer=self.tokenizers[model_path]
121
+ )
122
+
123
+ self.models[model_path] = model
124
+ logger.info(f"Model loaded successfully: {model_path}")
125
+ except Exception as e:
126
+ logger.error(f"Error loading model {model_path}: {str(e)}")
127
+ raise
128
+
129
+ @spaces.GPU(duration=120) # GPUを120秒間確保
130
+ async def generate_text(self, model_path: str, text: str) -> str:
131
+ """テキスト生成の実行"""
132
+ if model_path not in self.models:
133
+ await self.load_model(model_path, "text-generation")
134
+
135
+ try:
136
+ outputs = self.pipelines[model_path](
137
+ text,
138
+ max_new_tokens=100,
139
+ do_sample=True,
140
+ temperature=0.7,
141
+ top_p=0.9,
142
+ num_return_sequences=1
143
+ )
144
+ return outputs[0]["generated_text"]
145
+ except Exception as e:
146
+ logger.error(f"Error in text generation with {model_path}: {str(e)}")
147
+ raise
148
+
149
+ @spaces.GPU(duration=60) # GPUを60秒間確保
150
+ async def classify_text(self, model_path: str, text: str) -> str:
151
+ """テキスト分類の実行"""
152
+ if model_path not in self.models:
153
+ await self.load_model(model_path, "text-classification")
154
+
155
+ try:
156
+ result = self.pipelines[model_path](text)
157
+ return str(result)
158
+ except Exception as e:
159
+ logger.error(f"Error in classification with {model_path}: {str(e)}")
160
+ raise
161
+
162
+ class ModelManager:
163
+ def __init__(self):
164
+ self.api_clients = {}
165
+ self.local_manager = LocalModelManager()
166
+ self._initialize_clients()
167
+
168
+ def _initialize_clients(self):
169
+ """Inference APIクライアントの初期化"""
170
+ for model in TEXT_GENERATION_MODELS + CLASSIFICATION_MODELS:
171
+ if model.type == ModelType.INFERENCE_API and model.model_id:
172
+ self.api_clients[model.model_id] = AsyncInferenceClient(model.model_id)
173
+
174
+ async def run_text_generation(self, text: str, selected_types: List[str]) -> List[str]:
175
+ """テキスト生成モデルの実行"""
176
+ results = []
177
+ for model in TEXT_GENERATION_MODELS:
178
+ if model.type.value in selected_types:
179
+ try:
180
+ if model.type == ModelType.INFERENCE_API:
181
+ logger.info(f"Running API text generation: {model.name}")
182
+ response = await self.api_clients[model.model_id].text_generation(
183
+ text, max_new_tokens=100, temperature=0.7
184
+ )
185
+ results.append(f"{model.name}: {response}")
186
+ else:
187
+ logger.info(f"Running local text generation: {model.name}")
188
+ response = await self.local_manager.generate_text(model.model_path, text)
189
+ results.append(f"{model.name}: {response}")
190
+ except Exception as e:
191
+ logger.error(f"Error in {model.name}: {str(e)}")
192
+ results.append(f"{model.name}: Error - {str(e)}")
193
+ return results
194
+
195
+ async def run_classification(self, text: str, selected_types: List[str]) -> List[str]:
196
+ """分類モデルの実行"""
197
+ results = []
198
+ for model in CLASSIFICATION_MODELS:
199
+ if model.type.value in selected_types:
200
+ try:
201
+ if model.type == ModelType.INFERENCE_API:
202
+ logger.info(f"Running API classification: {model.name}")
203
+ response = await self.api_clients[model.model_id].text_classification(text)
204
+ results.append(f"{model.name}: {response}")
205
+ else:
206
+ logger.info(f"Running local classification: {model.name}")
207
+ response = await self.local_manager.classify_text(model.model_path, text)
208
+ results.append(f"{model.name}: {response}")
209
+ except Exception as e:
210
+ logger.error(f"Error in {model.name}: {str(e)}")
211
+ results.append(f"{model.name}: Error - {str(e)}")
212
+ return results
213
+
214
+ class UIComponents:
215
+ def __init__(self):
216
+ self.input_text = None
217
+ self.filter_checkboxes = None
218
+ self.invoke_button = None
219
+ self.gen_model_outputs = []
220
+ self.class_model_outputs = []
221
+ self.community_output = None
222
+
223
+ def create_header(self):
224
+ """ヘッダーセクションの作成"""
225
+ return gr.Markdown("""
226
+ # Toxic Total
227
+ This system evaluates the toxicity level of input text using multiple approaches.
228
+ """)
229
+
230
+ def create_input_section(self):
231
+ """入力セクションの作成"""
232
+ with gr.Row():
233
+ self.input_text = gr.Textbox(
234
+ label="Input Text",
235
+ placeholder="Enter text to analyze...",
236
+ lines=3
237
+ )
238
+
239
+ def create_filter_section(self):
240
+ """フィルターセクションの作成"""
241
+ with gr.Row():
242
+ self.filter_checkboxes = gr.CheckboxGroup(
243
+ choices=[t.value for t in ModelType],
244
+ value=[t.value for t in ModelType],
245
+ label="Filter Models",
246
+ info="Choose which types of models to display",
247
+ interactive=True
248
+ )
249
+
250
+ def create_invoke_button(self):
251
+ """Invokeボタンの作成"""
252
+ with gr.Row():
253
+ self.invoke_button = gr.Button(
254
+ "Invoke Selected Models",
255
+ variant="primary",
256
+ size="lg"
257
+ )
258
+
259
+ def create_model_grid(self, models: List[ModelConfig]) -> List[Dict]:
260
+ """モデルグリッドの作成"""
261
+ outputs = []
262
+ with gr.Column() as container:
263
+ for i in range(0, len(models), 2):
264
+ with gr.Row() as row:
265
+ for j in range(min(2, len(models) - i)):
266
+ model = models[i + j]
267
+ with gr.Column():
268
+ with gr.Group() as group:
269
+ gr.Markdown(f"### {model.name}")
270
+ gr.Markdown(f"Type: {model.type.value}")
271
+ output = gr.Textbox(
272
+ label="Model Output",
273
+ lines=5,
274
+ interactive=False,
275
+ info=model.description
276
+ )
277
+ outputs.append({
278
+ "type": model.type.value,
279
+ "name": model.name,
280
+ "output": output,
281
+ "group": group
282
+ })
283
+ return outputs
284
+
285
+ def create_model_tabs(self):
286
+ """モデルタブの作成"""
287
+ with gr.Tabs():
288
+ with gr.Tab("Text Generation LLM"):
289
+ self.gen_model_outputs = self.create_model_grid(TEXT_GENERATION_MODELS)
290
+ with gr.Tab("Classification LLM"):
291
+ self.class_model_outputs = self.create_model_grid(CLASSIFICATION_MODELS)
292
+ with gr.Tab("Community (Not implemented)"):
293
+ with gr.Column():
294
+ self.community_output = gr.Textbox(
295
+ label="Related Community Topics",
296
+ lines=5,
297
+ interactive=False
298
+ )
299
+
300
+ class ToxicityApp:
301
+ def __init__(self):
302
+ self.ui = UIComponents()
303
+ self.model_manager = ModelManager()
304
+
305
+ def update_model_visibility(self, selected_types: List[str]) -> List[gr.update]:
306
+ """モデルの表示状態を更新"""
307
+ logger.info(f"Updating visibility for types: {selected_types}")
308
+
309
+ updates = []
310
+ for outputs in [self.ui.gen_model_outputs, self.ui.class_model_outputs]:
311
+ for output in outputs:
312
+ visible = output["type"] in selected_types
313
+ logger.info(f"Model {output['name']} (type: {output['type']}): visible = {visible}")
314
+ updates.append(gr.update(visible=visible))
315
+ return updates
316
+
317
+ async def handle_invoke(self, text: str, selected_types: List[str]) -> List[str]:
318
+ """Invokeボタンのハンドラ"""
319
+ gen_results = await self.model_manager.run_text_generation(text, selected_types)
320
+ class_results = await self.model_manager.run_classification(text, selected_types)
321
+
322
+ # 結果リストの長さを調整
323
+ gen_results.extend([""] * (len(TEXT_GENERATION_MODELS) - len(gen_results)))
324
+ class_results.extend([""] * (len(CLASSIFICATION_MODELS) - len(class_results)))
325
+
326
+ return gen_results + class_results
327
+
328
+ def create_ui(self):
329
+ """UIの作成"""
330
+ with gr.Blocks() as demo:
331
+ self.ui.create_header()
332
+ self.ui.create_input_section()
333
+ self.ui.create_filter_section()
334
+ self.ui.create_invoke_button()
335
+ self.ui.create_model_tabs()
336
+
337
+ # イベントハンドラの設定
338
+ self.ui.filter_checkboxes.change(
339
+ fn=self.update_model_visibility,
340
+ inputs=[self.ui.filter_checkboxes],
341
+ outputs=[
342
+ output["group"]
343
+ for outputs in [self.ui.gen_model_outputs, self.ui.class_model_outputs]
344
+ for output in outputs
345
+ ]
346
+ )
347
+
348
+ self.ui.invoke_button.click(
349
+ fn=self.handle_invoke,
350
+ inputs=[self.ui.input_text, self.ui.filter_checkboxes],
351
+ outputs=[
352
+ output["output"]
353
+ for outputs in [self.ui.gen_model_outputs, self.ui.class_model_outputs]
354
+ for output in outputs
355
+ ]
356
+ )
357
+
358
+ return demo
359
+
360
+ def main():
361
+ app = ToxicityApp()
362
+ demo = app.create_ui()
363
  demo.launch()
364
+
365
+ if __name__ == "__main__":
366
+ main()
requirements.txt CHANGED
@@ -1 +1,7 @@
1
- huggingface_hub==0.25.2
 
 
 
 
 
 
 
1
+ gradio>=4.0.0
2
+ huggingface_hub
3
+ transformers
4
+ torch
5
+ accelerate
6
+ aiohttp
7
+ spaces