Spaces:
Running
Running
| test/adversarial_test.py | |
| import torch | |
| from transformers import AutoModelForCausalLM, AutoTokenizer | |
| from art.attacks.evasion import TextLaserAttack | |
| from art.estimators.language import HuggingFaceLanguageModel | |
| import requests | |
| # =========================== | |
| # تنظیمات اسپیس | |
| # =========================== | |
| SPACE_URL = "https://huggingface.co/spaces/code5ecure/Yavar.space/run/predict" | |
| HEADERS = {"Content-Type": "application/json"} | |
| # =========================== | |
| # نمونه متون برای تست | |
| # =========================== | |
| sample_texts = [ | |
| "Hello, how are you?", | |
| "Tell me a nice word about flowers." | |
| ] | |
| tokenizer = AutoTokenizer.from_pretrained("gpt2") | |
| model = AutoModelForCausalLM.from_pretrained("gpt2") | |
| art_model = HuggingFaceLanguageModel(model=model, tokenizer=tokenizer) | |
| attack = TextLaserAttack(estimator=art_model) | |
| for text in sample_texts: | |
| # اجرای حمله | |
| adv_text = attack.generate(x=[text])[0] | |
| # ارسال متن adversarial به اسپیس | |
| payload = {"data": [adv_text]} | |
| try: | |
| response = requests.post(SPACE_URL, headers=HEADERS, json=payload) | |
| output = response.json() | |
| except Exception as e: | |
| output = {"error": str(e)} | |
| print("Original: ", text) | |
| print("Adversarial: ", adv_text) | |
| print("Response: ", output) | |
| print("="*50) | |