Spaces:
Sleeping
Sleeping
Create text_processor.py
Browse files- text_processor.py +23 -0
text_processor.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
# Function for generating text based on input
|
| 3 |
+
def generate_text(input_text, model, tokenizer):
|
| 4 |
+
# Append the special token to the input
|
| 5 |
+
input_text = input_text + ' [LABEL]'
|
| 6 |
+
input_ids = tokenizer.encode(input_text, return_tensors='pt')
|
| 7 |
+
attention_mask = torch.ones_like(input_ids)
|
| 8 |
+
outputs = model.generate(input_ids, attention_mask=attention_mask, max_length=len(input_ids) + 5, do_sample=True, top_p=0.95)
|
| 9 |
+
generated = tokenizer.decode(outputs[0], skip_special_tokens=False)
|
| 10 |
+
labels = generated.split(',')
|
| 11 |
+
labels = [label.replace('[LABEL]', '').strip() for label in labels]
|
| 12 |
+
return generated
|
| 13 |
+
|
| 14 |
+
# Function for sequence classification
|
| 15 |
+
def classify_text(input_text, model, tokenizer):
|
| 16 |
+
# Tokenize the input text
|
| 17 |
+
input_ids = tokenizer.encode(input_text, return_tensors='pt')
|
| 18 |
+
attention_mask = torch.ones_like(input_ids)
|
| 19 |
+
# Perform sequence classification
|
| 20 |
+
result = model(input_ids, attention_mask=attention_mask)
|
| 21 |
+
# Post-process the results (e.g., select labels based on a threshold)
|
| 22 |
+
labels = post_process_labels(result)
|
| 23 |
+
return labels
|