Views
No views yet
# List of champions
champions = [
"aatrox", "ahri", "akali", "akshan", "alistar", "amumu", "anivia", "annie", "aphelios", "ashe",
"aurelionsol", "azir", "bard", "belveth", "blitzcrank", "brand", "braum", "caitlyn", "camille",
"cassiopeia", "chogath", "corki", "darius", "diana", "drmundo", "draven", "ekko", "elise",
"evelynn", "ezreal", "fiddlesticks", "fiora", "fizz", "galio", "gangplank", "garen", "gnar",
"gragas", "graves", "gwen", "hecarim", "heimerdinger", "illaoi", "irelia", "ivern", "janna",
"jarvaniv", "jax", "jayce", "jhin", "jinx", "kaisa", "kalista", "karma", "karthus", "kassadin",
"katarina", "kayle", "kayn", "kennen", "khazix", "kindred", "kled", "kogmaw", "leblanc", "leesin",
"leona", "lillia", "lissandra", "lucian", "lulu", "lux", "malphite", "malzahar", "maokai",
"masteryi", "milio", "missfortune", "mordekaiser", "morgana", "naafiri", "nami", "nasus",
"nautilus", "neeko", "nidalee", "nilah", "nocturne", "nunu", "olaf", "orianna", "ornn",
"pantheon", "poppy", "pyke", "qiyana", "quinn", "rakan", "rammus", "reksai", "rell", "renataglasc",
"renekton", "rengar", "riven", "rumble", "ryze", "samira", "sejuani", "senna", "seraphine", "sett",
"shaco", "shen", "shyvana", "singed", "sion", "sivir", "skarner", "sona", "soraka", "swain",
"sylas", "syndra", "tahmkench", "taliyah", "talon", "taric", "teemo", "thresh", "tristana",
"trundle", "tryndamere", "twistedfate", "twitch", "udyr", "urgot", "varus", "vayne", "veigar",
"velkoz", "vex", "vi", "viego", "viktor", "vladimir", "volibear", "warwick", "monkeyking", "xayah",
"xerath", "xinzhao", "yasuo", "yone", "yorick", "yuumi", "zac", "zed", "ziggs", "zilean", "zoe", "zyra"
]
print(f"The total number of champions: {len(champions)}")
# Base URL for the champion story in Korean
base_url = "https://universe.leagueoflegends.com/ko_KR/story/champion/"
# Function to scrape the Korean name and background story of a champion
def scrape_champion_data(champion):
url = base_url + champion + "/"
response = requests.get(url)
if response.status_code == 200:
soup = BeautifulSoup(response.content, 'html.parser')
# Extract the Korean name from the <title> tag
korean_name = soup.find('title').text.split('-')[0].strip()
# Extract the background story from the meta description
meta_description = soup.find('meta', {'name': 'description'})
if meta_description:
background_story = meta_description.get('content').replace('\n', ' ').strip()
else:
background_story = "No background story available"
return korean_name, background_story
else:
return None, None
# Open the CSV file for writing
with open("champion_bs.csv", "w", newline='', encoding='utf-8') as csvfile:
# Define the column headers
fieldnames = ['url-name', 'korean-name', 'background-story']
# Create a CSV writer object
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
# Write the header
writer.writeheader()
# Scrape data for each champion and write to CSV
for champion in champions:
korean_name, background_story = scrape_champion_data(champion)
if korean_name and background_story:
writer.writerow({
'url-name': champion,
'korean-name': korean_name,
'background-story': background_story
})
print(f"Scraped data for {champion}: {korean_name}")
else:
print(f"Failed to scrape data for {champion}")
print("Data scraping complete. Saved to champion_bs.csv")1import torch
2from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
3
4model_id = "google/gemma-2-2b-it"
5
6bnb_config = BitsAndBytesConfig(
7 load_in_4bit=True,
8 bnb_4bit_use_double_quant=True,
9 bnb_4bit_quant_type="nf4",
10 bnb_4bit_compute_dtype=torch.bfloat16
11)
12
13model = AutoModelForCausalLM.from_pretrained(
14 model_id,
15 quantization_config=qlora_config,
16 device_map="auto",
17 attn_implementation=attn_implementation
18)
19
20tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)1from peft import LoraConfig, get_peft_model
2
3def find_linear_layers(model):
4 linear_layers = set()
5 for name, module in model.named_modules():
6 if isinstance(module, bnb.nn.Linear4bit):
7 names = name.split('.')
8 layer_name = names[-1]
9 if layer_name != 'lm_head':
10 linear_layers.add(layer_name)
11 return list(linear_layers)
12
13lora_target_modules = find_linear_layers(model)
14
15lora_config = LoraConfig(
16 r=64,
17 lora_alpha=32,
18 target_modules=lora_target_modules,
19 lora_dropout=0.05,
20 bias="none",
21 task_type="CAUSAL_LM"
22)
23
24model = get_peft_model(model, lora_config)1data = [
2{ "q": "대부분의 필멸자가 알고 있는 현실 차원은 무엇인가?", "a": "대부분의 필멸자는 물질 세계라는 하나의 현실 차원만 알고 있다." },
3{ "q": "오로라가 유년 시절을 보낸 곳은 어디인가?", "a": "오로라는 브뤼니 부족의 고향이자 외딴 마을인 아무우에서 유년 시절을 보냈다." },
4{ "q": "오로라가 자신을 이해해준 유일한 가족 구성원은 누구인가?", "a": "오로라의 이모할머니 하부우가 오로라를 진심으로 받아들였다." },
5...]
6
7qa_df = pd.DataFrame(data, columns=["q", "a"])
8qa_dataset = Dataset.from_pandas(qa_df)1<start_of_turn>user
2{Qustion}<end_of_turn>
3<start_of_turn>model
4{Answer}
5<end_of_turn>1def format_chat_prompt(example):
2 chat_data = [
3 {"role": "user", "content": example["q"]},
4 {"role": "assistant", "content": example["a"]}
5 ]
6 example["text"] = tokenizer.apply_chat_template(chat_data, tokenize=False)
7 return example
8
9dataset = dataset.map(format_chat_prompt, num_proc=4)<bos>
<start_of_turn>user
아트록스가 태어난 곳은 어디인가?<end_of_turn>
<start_of_turn>model
아트록스는 슈리마에서 태어났다.<end_of_turn>'}1import transformers
2from trl import SFTTrainer
3
4# Training arguments
5training_args = TrainingArguments(
6 output_dir=OUTPUT_MODEL_PATH,
7 per_device_train_batch_size=1, # steps_per_epoch = ceil(total_samples / (batch_size * gradient_accumulation_steps))
8 gradient_accumulation_steps=10, # total_samples means len(dataset)
9 num_train_epochs=10,
10 learning_rate=2e-4,
11 fp16=False,
12 bf16=False,
13 logging_steps=len(dataset)//10,
14 optim="paged_adamw_32bit",
15 logging_dir="./logs",
16 save_strategy="epoch",
17 evaluation_strategy="no",
18 do_eval=False,
19 group_by_length=True,
20 report_to="none"
21)
22
23# Initialize trainer
24trainer = SFTTrainer(
25 model=model,
26 train_dataset=dataset,
27 peft_config=lora_config,
28 dataset_text_field="text",
29 max_seq_length=512,
30 tokenizer=tokenizer,
31 args=training_args,
32 packing=False,
33)
34
35# Train the model
36trainer.train()1def generate_response(prompt, model, tokenizer, temperature=0.1):
2 formatted_prompt=f"""<start_of_turn>user
3{prompt}<end_of_turn>
4<start_of_turn>model
5"""
6 inputs = tokenizer(formatted_prompt, return_tensors="pt").to("cuda")
7 outputs = model.generate(
8 **inputs,
9 max_new_tokens=256,
10 do_sample=temperature > 0,
11 temperature=temperature
12 )
13 return tokenizer.decode(outputs[0], skip_special_tokens=False)1prompt = "조이는 아우렐리온 솔한테 무슨 약속을 했어?"
2response = generate_response(prompt, model, tokenizer)
3print(response)조이는 아우렐리온 솔을 지키기 위해 할 수 있는 것은 무엇이든 해주리라 약속했다.<bos><start_of_turn>user
조이는 아우렐리온 솔한테 무슨 약속을 했어?<end_of_turn>
<start_of_turn>model
조이는 아우렐리온 솔을 지키기 위해 할 수 있는 것은 무엇이든 해주리라 약속했다.<end_of_turn><bos><start_of_turn>user
조이는 아우렐리온 솔한테 무슨 약속을 했어?<end_of_turn>
<start_of_turn>model
조이는 아우렐리온 솔한테 **무슨 약속을 했는지**에 대한 정보는 아직 알려지지 않았습니다.
조이는 아우렐리온 솔한테 약속을 했는지에 대한 이야기는 몇 가지 유행하는 밈과 관련된 것으로 보입니다.
* **아우렐리온 솔:** 이것은 2023년 1월에 출시된 아우렐리온 솔의 이름입니다.
* **조이:** 이것은 2023년 1월에 출시된 아우렐리온 솔의 이름입니다.
이러한 밈들은 흥미롭지만, 실제로 조이는 아우렐리온 솔한테 무슨 약속을 했는지에 대한 정확한 정보는 아직 알려지지 않았습니다.
<end_of_turn>