Views
No views yet
google/gemma-3-270mBitsAndBytesConfig (load_in_4bit=True, bnb_4bit_quant_type="nf4", bnb_4bit_compute_dtype=torch.bfloat16)peft.LoraConfig)transformers.TrainingArguments)1import os
2import torch
3from dotenv import load_dotenv
4from transformers import AutoModelForCausalLM, AutoTokenizer
5
6load_dotenv()
7
8HF_TOKEN = os.getenv("HF_TOKEN")
9print(f"HF_TOKEN found: {HF_TOKEN is not None}")
10
11modelUrl = "manulthanura/Gemma-3-270m-Cyberbullying-Classifier"
12model = AutoModelForCausalLM.from_pretrained(modelUrl, token=HF_TOKEN)
13
14tokenizer = AutoTokenizer.from_pretrained(modelUrl, token=HF_TOKEN)
15tokenizer.pad_token = tokenizer.eos_token
16tokenizer.padding_side = "right"
17
18bullyingCategories = ['gender', 'religion', 'age', 'ethnicity', 'other_cyberbullying']
19
20def format_prompt_inference(text, categories=bullyingCategories):
21 return f"""Classify the given content into one of these cyberbullying categories: {categories} or not_cyberbullying if not.
22
23 Categories and definitions:
24 - gender: Harassment based on gender identity or expression
25 - religion: Discrimination or harassment targeting religious beliefs
26 - ethnicity: Racial or ethnic-based harassment
27 - age: Discrimination based on someone's age
28 - other_cyberbullying: Other forms of online harassment
29 - not_cyberbullying: Non-harmful communication
30
31 Output only one category most relevant to the content. If none apply, respond with not_cyberbullying. Always respond with only one word from the categories.
32 example:
33 input: Hello everyone, I hope you are having a great day!
34 output: not_cyberbullying
35
36 input: {text}
37 output: One of the categories {categories} or not_cyberbullying"""
38
39def process_text(text):
40 # Format the input text
41 prompt = format_prompt_inference(text, categories=bullyingCategories)
42
43 # Tokenize the input
44 input_ids = tokenizer(prompt, return_tensors="pt").to(model.device)
45
46 # Generate a prediction
47 with torch.no_grad():
48 outputs = model.generate(
49 **input_ids,
50 max_new_tokens=20,
51 num_return_sequences=1,
52 pad_token_id=tokenizer.eos_token_id
53 )
54
55 # Decode the output
56 decoded_output = tokenizer.decode(outputs[0], skip_special_tokens=True)
57
58 # Post-process the generated output to extract the classification
59 predicted_output_raw = decoded_output.replace(prompt, "").strip()
60 predicted_type = predicted_output_raw.split('\n')[0].strip()
61
62 # Update the logic to determine if it's cyberbullying
63 is_cyberbullying = predicted_type.lower().strip() in bullyingCategories
64
65 return is_cyberbullying, predicted_type
66
67def main():
68 print("\nCyberbullying Text Analyzer")
69 print("==========================")
70 print("\nModel loaded and ready for analysis.")
71
72 while True:
73 print("\nEnter text to analyze (or 'q' to exit):")
74 text = input().strip()
75
76 if text.lower() == 'q':
77 print("\nExiting program...")
78 break
79
80 if not text:
81 print("Please enter some text.")
82 continue
83
84 print("\nAnalyzing...")
85 is_cyberbullying, predicted_type = process_text(text)
86
87 print("\n--- Analysis Result ---")
88 print(f"cyberbullying: {is_cyberbullying}, type: {predicted_type}")
89
90if __name__ == "__main__":
91 main()