-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstimuli.py
More file actions
184 lines (139 loc) · 5.39 KB
/
stimuli.py
File metadata and controls
184 lines (139 loc) · 5.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
# stimuli.py - Wersja dla single-word paradigm
# Ładuje słowa i zdania z pliku zdania.txt
import logging
import random
import re
from dataclasses import dataclass, field
from pathlib import Path
from typing import List, Optional, Tuple
@dataclass
class WordTrial:
"""Pojedynczy trial słowny."""
word: str
word_index: int # Indeks słowa w liście unikalnych słów
repetition: int # Która to powtórka (1..K)
trial_index: int = 0 # Globalny indeks trialu (ustawiany po shuffle)
@dataclass
class SentenceTrial:
"""Pojedynczy trial zdaniowy (test)."""
sentence: str
words: List[str]
sentence_index: int
class StimulusManager:
"""Zarządza słowami i zdaniami dla eksperymentu EEG2Text."""
def __init__(
self,
logger: logging.Logger,
words_file: str = "zdania.txt",
sentences_file: str = "zdania.txt",
):
self.logger = logger
self.words_file = Path(words_file)
self.sentences_file = Path(sentences_file)
self.all_words: List[str] = []
self.all_sentences: List[str] = []
self._load_data()
def _load_data(self):
"""Ładuje słowa i zdania z pliku zdania.txt."""
if not self.words_file.exists():
raise FileNotFoundError(f"Nie znaleziono pliku: {self.words_file}")
content = self.words_file.read_text(encoding="utf-8")
self.all_sentences = self._parse_sentences(content)
self.logger.info(
f"Załadowano {len(self.all_sentences)} zdań z {self.words_file}"
)
self.all_words = self._parse_words(content)
self.logger.info(f"Załadowano {len(self.all_words)} słów z {self.words_file}")
def _parse_sentences(self, content: str) -> List[str]:
"""Parsuje zdania z pliku (format: ' 1. Mama daje kwiat tu.')"""
sentences = []
in_sentences = False
for line in content.split("\n"):
line = line.strip()
if "PROSTYCH ZDAŃ" in line or "ZDAŃ W JĘZYKU" in line:
in_sentences = True
continue
if "LISTA UŻYTYCH SŁÓW" in line:
break
if line.startswith("===") or not line:
continue
if in_sentences:
match = re.match(r"\d+\.\s+(.+)", line)
if match:
sentences.append(match.group(1).strip())
return sentences
def _parse_words(self, content: str) -> List[str]:
"""Parsuje listę słów z pliku (format: ' 1. ale')"""
words = []
in_words = False
for line in content.split("\n"):
line = line.strip()
if "LISTA UŻYTYCH SŁÓW" in line:
in_words = True
continue
if in_words:
if line.startswith("===") or not line or line.startswith("✓"):
continue
match = re.match(r"\d+\.\s+(.+)", line)
if match:
words.append(match.group(1).strip())
return words
def get_word_trials(self, n_words: int, k_repeats: int) -> List[WordTrial]:
"""
Generuje listę trialli słownych.
Args:
n_words: Ile unikalnych słów (max len(self.all_words))
k_repeats: Ile powtórzeń każdego słowa
Returns:
Zshufflowana lista WordTrial (N * K elementów)
"""
n_words = min(n_words, len(self.all_words))
selected_words = random.sample(self.all_words, n_words)
self.logger.info(
f"Wybrano {n_words} słów, {k_repeats} powtórzeń = {n_words * k_repeats} trialli"
)
trials = []
for word_idx, word in enumerate(selected_words):
for rep in range(1, k_repeats + 1):
trials.append(WordTrial(word=word, word_index=word_idx, repetition=rep))
random.shuffle(trials)
for i, trial in enumerate(trials):
trial.trial_index = i
self.logger.info(
f"Wygenerowano {len(trials)} trialli słownych (zshufflowanych)"
)
return trials
def get_sentence_trials(
self, m_sentences: int, used_words: Optional[List[str]] = None
) -> List[SentenceTrial]:
"""
Losuje M zdań testowych.
Args:
m_sentences: Ile zdań
used_words: Opcjonalnie filtruj zdania zawierające te słowa
Returns:
Lista SentenceTrial
"""
available = self.all_sentences.copy()
if used_words:
used_set = set(w.lower() for w in used_words)
filtered = [
s
for s in available
if any(w.lower() in used_set for w in s.replace(".", "").split())
]
if len(filtered) >= m_sentences:
available = filtered
self.logger.info(
f"Przefiltrowano do {len(available)} zdań zawierających słowa z sesji"
)
m_sentences = min(m_sentences, len(available))
selected = random.sample(available, m_sentences)
trials = []
for i, sentence in enumerate(selected):
words = sentence.replace(".", "").split()
trials.append(
SentenceTrial(sentence=sentence, words=words, sentence_index=i)
)
self.logger.info(f"Wygenerowano {len(trials)} zdań testowych")
return trials