rust-pgn-reader-python-binding 0.1.0__tar.gz → 1.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -55,9 +55,9 @@ checksum = "b248f5224d1d606005e02c97f5aa4e88eeb230488bcc03bc9ca4d7991399f2b5"
55
55
 
56
56
  [[package]]
57
57
  name = "libc"
58
- version = "0.2.168"
58
+ version = "0.2.169"
59
59
  source = "registry+https://github.com/rust-lang/crates.io-index"
60
- checksum = "5aaeb2981e0606ca11d79718f8bb01164f1d6ed75080182d3abf017e6d244b6d"
60
+ checksum = "b5aba8db14291edd000dfcc4d620c7ebfb122c613afb886ca8803fa4e128a20a"
61
61
 
62
62
  [[package]]
63
63
  name = "memchr"
@@ -74,12 +74,28 @@ dependencies = [
74
74
  "autocfg",
75
75
  ]
76
76
 
77
+ [[package]]
78
+ name = "minimal-lexical"
79
+ version = "0.2.1"
80
+ source = "registry+https://github.com/rust-lang/crates.io-index"
81
+ checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
82
+
77
83
  [[package]]
78
84
  name = "nohash-hasher"
79
85
  version = "0.2.0"
80
86
  source = "registry+https://github.com/rust-lang/crates.io-index"
81
87
  checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451"
82
88
 
89
+ [[package]]
90
+ name = "nom"
91
+ version = "7.1.3"
92
+ source = "registry+https://github.com/rust-lang/crates.io-index"
93
+ checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"
94
+ dependencies = [
95
+ "memchr",
96
+ "minimal-lexical",
97
+ ]
98
+
83
99
  [[package]]
84
100
  name = "num-traits"
85
101
  version = "0.2.19"
@@ -196,8 +212,9 @@ dependencies = [
196
212
 
197
213
  [[package]]
198
214
  name = "rust_pgn_reader_python_binding"
199
- version = "0.1.0"
215
+ version = "1.1.0"
200
216
  dependencies = [
217
+ "nom",
201
218
  "pgn-reader",
202
219
  "pyo3",
203
220
  "shakmaty",
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "rust_pgn_reader_python_binding"
3
- version = "0.1.0"
3
+ version = "1.1.0"
4
4
  edition = "2021"
5
5
 
6
6
  # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@@ -12,3 +12,4 @@ crate-type = ["cdylib"]
12
12
  pyo3 = "0.23.3"
13
13
  shakmaty = "0.27"
14
14
  pgn-reader = "0.26.0"
15
+ nom = "7.1.3"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: rust_pgn_reader_python_binding
3
- Version: 0.1.0
3
+ Version: 1.1.0
4
4
  Classifier: Programming Language :: Rust
5
5
  Classifier: Programming Language :: Python :: Implementation :: CPython
6
6
  Classifier: Programming Language :: Python :: Implementation :: PyPy
@@ -0,0 +1,250 @@
1
+ use nom::{
2
+ branch::alt,
3
+ bytes::complete::{is_not, tag},
4
+ character::complete::{char, digit1},
5
+ combinator::{map, opt, recognize},
6
+ multi::{many0, many1},
7
+ sequence::{delimited, pair, preceded, tuple},
8
+ IResult,
9
+ };
10
+
11
+ #[derive(Debug, PartialEq)]
12
+ pub enum CommentContent {
13
+ Text(String),
14
+ Eval(f64),
15
+ ClkTime((u32, u8, f64)),
16
+ }
17
+
18
+ pub fn parse_comments(input: &str) -> IResult<&str, Vec<CommentContent>> {
19
+ many0(alt((
20
+ map(tag_parser, |s| match s.as_str() {
21
+ eval if eval.starts_with("[eval ") => {
22
+ let value = &eval[6..eval.len() - 1];
23
+ CommentContent::Eval(value.parse().unwrap_or_default())
24
+ }
25
+ clk if clk.starts_with("[clk ") => {
26
+ let time_parts: Vec<&str> = clk[5..clk.len() - 1].split(':').collect();
27
+ let hours = time_parts
28
+ .get(0)
29
+ .and_then(|h| h.parse().ok())
30
+ .unwrap_or_default();
31
+ let minutes = time_parts
32
+ .get(1)
33
+ .and_then(|m| m.parse().ok())
34
+ .unwrap_or_default();
35
+ let seconds = time_parts
36
+ .get(2)
37
+ .and_then(|s| s.parse().ok())
38
+ .unwrap_or_default();
39
+ CommentContent::ClkTime((hours, minutes, seconds))
40
+ }
41
+ _ => unreachable!(),
42
+ }),
43
+ map(text, |s| CommentContent::Text(s.to_string())),
44
+ )))(input)
45
+ }
46
+
47
+ /// Parser for a tag
48
+ fn tag_parser(input: &str) -> IResult<&str, String> {
49
+ delimited(
50
+ tuple((char('['), char('%'))),
51
+ alt((eval_parser, clk_parser)),
52
+ char(']'),
53
+ )(input)
54
+ }
55
+
56
+ /// Parser for an eval tag
57
+ fn eval_parser(input: &str) -> IResult<&str, String> {
58
+ map(
59
+ tuple((tag("eval"), spacing, alt((signed_number, mate_eval)))),
60
+ |(_, _, value)| format!("[eval {}]", value),
61
+ )(input)
62
+ }
63
+
64
+ /// Parser for a clk tag
65
+ fn clk_parser(input: &str) -> IResult<&str, String> {
66
+ map(tuple((tag("clk"), spacing, time_value)), |(_, _, value)| {
67
+ format!("[clk {}]", value)
68
+ })(input)
69
+ }
70
+
71
+ /// Parser for a signed number
72
+ fn signed_number(input: &str) -> IResult<&str, String> {
73
+ map(
74
+ recognize(pair(
75
+ opt(alt((char('+'), char('-')))),
76
+ recognize(pair(digit1, opt(preceded(char('.'), digit1)))),
77
+ )),
78
+ |s: &str| s.to_string(),
79
+ )(input)
80
+ }
81
+
82
+ fn mate_eval(input: &str) -> IResult<&str, String> {
83
+ let signed_integer = recognize(tuple((
84
+ opt(char('-')), // Optional minus sign
85
+ digit1, // One or more digits
86
+ )));
87
+ map(preceded(char('#'), signed_integer), String::from)(input)
88
+ }
89
+
90
+ /// Parser for a time value
91
+ fn time_value(input: &str) -> IResult<&str, String> {
92
+ map(
93
+ tuple((
94
+ digit1, // Hours
95
+ char(':'), // Colon separator
96
+ digit1, // Minutes
97
+ char(':'), // Colon separator
98
+ digit1, // Seconds
99
+ opt(preceded(
100
+ char('.'), // Dot separator
101
+ digit1, // Fractional seconds
102
+ )),
103
+ )),
104
+ |(h, _, m, _, s, frac)| match frac {
105
+ Some(f) => format!("{}:{}:{}.{}", h, m, s, f),
106
+ None => format!("{}:{}:{}", h, m, s),
107
+ },
108
+ )(input)
109
+ }
110
+
111
+ /// Parser for text (any characters except '[' and ']')
112
+ fn text(input: &str) -> IResult<&str, &str> {
113
+ is_not("[]")(input)
114
+ }
115
+
116
+ /// Parser for spacing (one or more spaces)
117
+ fn spacing(input: &str) -> IResult<&str, &str> {
118
+ recognize(many1(char(' ')))(input)
119
+ }
120
+
121
+ #[cfg(test)]
122
+ mod tests {
123
+ use super::*;
124
+
125
+ #[test]
126
+ fn test_comments1() {
127
+ let input = "[%eval 123] some text [%clk 12:34:56]";
128
+ let result = parse_comments(input);
129
+ assert!(result.is_ok());
130
+ let (remaining, parsed) = result.unwrap();
131
+ assert_eq!(
132
+ parsed,
133
+ vec![
134
+ CommentContent::Eval(123.0),
135
+ CommentContent::Text(" some text ".to_string()),
136
+ CommentContent::ClkTime((12, 34, 56.0))
137
+ ]
138
+ );
139
+ assert_eq!(remaining, "");
140
+ }
141
+
142
+ #[test]
143
+ fn test_comments2() {
144
+ let input = "[%clk 12:34:56] some text ";
145
+ let result = parse_comments(input);
146
+ assert!(result.is_ok());
147
+ let (remaining, parsed) = result.unwrap();
148
+ assert_eq!(
149
+ parsed,
150
+ vec![
151
+ CommentContent::ClkTime((12, 34, 56.0)),
152
+ CommentContent::Text(" some text ".to_string())
153
+ ]
154
+ );
155
+ assert_eq!(remaining, "");
156
+ }
157
+
158
+ #[test]
159
+ fn test_comment_fractional_sec() {
160
+ let input = "[%clk 12:34:56.0123]";
161
+ let result = parse_comments(input);
162
+ assert!(result.is_ok());
163
+ let (remaining, parsed) = result.unwrap();
164
+ assert_eq!(parsed, vec![CommentContent::ClkTime((12, 34, 56.0123)),]);
165
+ assert_eq!(remaining, "");
166
+ }
167
+
168
+ #[test]
169
+ fn test_tag_parser() {
170
+ let input = "[%eval 123]";
171
+ let result = tag_parser(input);
172
+ assert!(result.is_ok());
173
+ let (remaining, parsed) = result.unwrap();
174
+ assert_eq!(parsed, "[eval 123]");
175
+ assert_eq!(remaining, "");
176
+ }
177
+
178
+ #[test]
179
+ fn test_eval_mate() {
180
+ let input = "[%eval #-3]";
181
+ let result = tag_parser(input);
182
+ assert!(result.is_ok());
183
+ let (remaining, parsed) = result.unwrap();
184
+ assert_eq!(parsed, "[eval -3]"); // TODO mark the mates
185
+ assert_eq!(remaining, "");
186
+ }
187
+
188
+ #[test]
189
+ fn test_tag_parser_incorrect_name() {
190
+ let input = "[%clk 123]";
191
+ let result = tag_parser(input);
192
+ assert!(result.is_err());
193
+ }
194
+
195
+ #[test]
196
+ fn test_clk_parser() {
197
+ let input = "clk 12:34:56";
198
+ let result = clk_parser(input);
199
+ assert!(result.is_ok());
200
+ let (remaining, parsed) = result.unwrap();
201
+ assert_eq!(parsed, "[clk 12:34:56]");
202
+ assert_eq!(remaining, "");
203
+ }
204
+ #[test]
205
+ fn test_clk_parser_incorrect_name() {
206
+ let input = "eval 123";
207
+ let result = clk_parser(input);
208
+ assert!(result.is_err());
209
+ }
210
+
211
+ #[test]
212
+ fn test_text() {
213
+ let input = "some text";
214
+ let result = text(input);
215
+ assert!(result.is_ok());
216
+ let (remaining, parsed) = result.unwrap();
217
+ assert_eq!(parsed, "some text");
218
+ assert_eq!(remaining, "");
219
+ }
220
+
221
+ #[test]
222
+ fn test_signed_number() {
223
+ let input = "-123.45";
224
+ let result = signed_number(input);
225
+ assert!(result.is_ok());
226
+ let (remaining, parsed) = result.unwrap();
227
+ assert_eq!(parsed, "-123.45");
228
+ assert_eq!(remaining, "");
229
+ }
230
+
231
+ #[test]
232
+ fn test_time_value() {
233
+ let input = "12:34:56";
234
+ let result = time_value(input);
235
+ assert!(result.is_ok());
236
+ let (remaining, parsed) = result.unwrap();
237
+ assert_eq!(parsed, "12:34:56");
238
+ assert_eq!(remaining, "");
239
+ }
240
+
241
+ #[test]
242
+ fn test_time_value_fractional() {
243
+ let input = "12:34:56.12345";
244
+ let result = time_value(input);
245
+ assert!(result.is_ok());
246
+ let (remaining, parsed) = result.unwrap();
247
+ assert_eq!(parsed, "12:34:56.12345");
248
+ assert_eq!(remaining, "");
249
+ }
250
+ }
@@ -0,0 +1,25 @@
1
+ import rust_pgn_reader_python_binding
2
+
3
+ pgn_moves = """
4
+ 1. e4 { [%eval 0.17] [%clk 0:00:30] } 1... c5 { [%eval 0.19] [%clk 0:00:30] }
5
+ 2. Nf3 { [%eval 0.25] [%clk 0:00:29] } 2... Nc6 { [%eval 0.33] [%clk 0:00:30] }
6
+ 3. Bc4 { [%eval -0.13] [%clk 0:00:28] } 3... e6 { [%eval -0.04] [%clk 0:00:30] }
7
+ 4. c3 { [%eval -0.4] [%clk 0:00:27] } 4... b5? { [%eval 1.18] [%clk 0:00:30] }
8
+ 5. Bb3?! { [%eval 0.21] [%clk 0:00:26] } 5... c4 { [%eval 0.32] [%clk 0:00:29] }
9
+ 6. Bc2 { [%eval 0.2] [%clk 0:00:25] } 6... a5 { [%eval 0.6] [%clk 0:00:29] }
10
+ 7. d4 { [%eval 0.29] [%clk 0:00:23] } 7... cxd3 { [%eval 0.6] [%clk 0:00:27] }
11
+ 8. Qxd3 { [%eval 0.12] [%clk 0:00:22] } 8... Nf6 { [%eval 0.52] [%clk 0:00:26] }
12
+ 9. e5 { [%eval 0.39] [%clk 0:00:21] } 9... Nd5 { [%eval 0.45] [%clk 0:00:25] }
13
+ 10. Bg5?! { [%eval -0.44] [%clk 0:00:18] } 10... Qc7 { [%eval -0.12] [%clk 0:00:23] }
14
+ 11. Nbd2?? { [%eval -3.15] [%clk 0:00:14] } 11... h6 { [%eval -2.99] [%clk 0:00:23] }
15
+ 12. Bh4 { [%eval -3.0] [%clk 0:00:11] } 12... Ba6? { [%eval -0.12] [%clk 0:00:23] }
16
+ 13. b3?? { [%eval -4.14] [%clk 0:00:02] } 13... Nf4? { [%eval -2.73] [%clk 0:00:21] } 0-1
17
+ """
18
+
19
+ extractor = rust_pgn_reader_python_binding.parse_moves(pgn_moves)
20
+
21
+ print(extractor.moves)
22
+ print(extractor.comments)
23
+ print(extractor.valid_moves)
24
+ print(extractor.evals)
25
+ print(extractor.clock_times)
@@ -0,0 +1,155 @@
1
+ use shakmaty::{uci::UciMove, Chess, Position};
2
+
3
+ use crate::comment_parsing::parse_comments;
4
+ use crate::comment_parsing::CommentContent;
5
+ use pgn_reader::{BufferedReader, RawComment, SanPlus, Skip, Visitor};
6
+ use pyo3::prelude::*;
7
+ use std::io::Cursor;
8
+
9
+ mod comment_parsing;
10
+
11
+ #[pyclass]
12
+ /// A Visitor to extract SAN moves and comments from PGN movetext
13
+ struct MoveExtractor {
14
+ #[pyo3(get)]
15
+ moves: Vec<String>,
16
+
17
+ #[pyo3(get)]
18
+ valid_moves: bool,
19
+
20
+ #[pyo3(get)]
21
+ comments: Vec<String>,
22
+
23
+ #[pyo3(get)]
24
+ evals: Vec<f64>,
25
+
26
+ #[pyo3(get)]
27
+ clock_times: Vec<(u32, u8, f64)>,
28
+
29
+ pos: Chess,
30
+ }
31
+
32
+ #[pymethods]
33
+ impl MoveExtractor {
34
+ #[new]
35
+ fn new() -> MoveExtractor {
36
+ MoveExtractor {
37
+ moves: Vec::with_capacity(100),
38
+ pos: Chess::default(),
39
+ valid_moves: true,
40
+ comments: Vec::with_capacity(100),
41
+ evals: Vec::with_capacity(100),
42
+ clock_times: Vec::with_capacity(100),
43
+ }
44
+ }
45
+ }
46
+
47
+ impl Visitor for MoveExtractor {
48
+ type Result = bool;
49
+
50
+ fn begin_game(&mut self) {
51
+ self.moves.clear();
52
+ self.pos = Chess::default();
53
+ self.valid_moves = true;
54
+ self.comments.clear();
55
+ self.evals.clear();
56
+ self.clock_times.clear();
57
+ }
58
+
59
+ fn san(&mut self, san_plus: SanPlus) {
60
+ if self.valid_moves {
61
+ match san_plus.san.to_move(&self.pos) {
62
+ Ok(m) => {
63
+ self.pos.play_unchecked(&m);
64
+ let uci = UciMove::from_standard(&m);
65
+ self.moves.push(uci.to_string());
66
+ }
67
+ Err(err) => {
68
+ eprintln!("error in game: {} {}", err, san_plus);
69
+ self.valid_moves = false;
70
+ }
71
+ }
72
+ }
73
+ }
74
+
75
+ fn comment(&mut self, _comment: RawComment<'_>) {
76
+ let comment = String::from_utf8_lossy(_comment.as_bytes()).into_owned();
77
+ match parse_comments(&comment) {
78
+ Ok((remaining_input, parsed_comments)) => {
79
+ if !remaining_input.is_empty() {
80
+ eprintln!("Unparsed remaining input: {:?}", remaining_input);
81
+ return;
82
+ }
83
+ let mut eval_encountered = false;
84
+ let mut clk_time_encountered = false;
85
+ let mut move_comments = String::new();
86
+
87
+ for content in parsed_comments {
88
+ match content {
89
+ CommentContent::Text(text) => {
90
+ if text.trim() != "" {
91
+ move_comments.push_str(&text);
92
+ }
93
+ }
94
+ CommentContent::Eval(eval_value) => {
95
+ if eval_encountered {
96
+ eprintln!("Multiple Eval values found in comment: {:?}", _comment);
97
+ return;
98
+ }
99
+ eval_encountered = true;
100
+ self.evals.push(eval_value);
101
+ }
102
+ CommentContent::ClkTime(clk_time) => {
103
+ if clk_time_encountered {
104
+ eprintln!(
105
+ "Multiple ClkTime values found in comment: {:?}",
106
+ _comment
107
+ );
108
+ return;
109
+ }
110
+ clk_time_encountered = true;
111
+ self.clock_times.push(clk_time);
112
+ }
113
+ }
114
+ }
115
+ self.comments.push(move_comments); // Add the concatenated comment string
116
+ }
117
+ Err(e) => {
118
+ eprintln!("Error parsing comment: {:?}", e);
119
+ }
120
+ }
121
+ }
122
+
123
+ fn begin_variation(&mut self) -> Skip {
124
+ Skip(true) // stay in the mainline
125
+ }
126
+
127
+ fn end_game(&mut self) -> Self::Result {
128
+ self.valid_moves
129
+ }
130
+ }
131
+
132
+ /// Parses PGN movetext and returns a list of SAN moves and parsed comments
133
+ #[pyfunction]
134
+ fn parse_moves(pgn: &str) -> PyResult<MoveExtractor> {
135
+ let mut reader = BufferedReader::new(Cursor::new(pgn));
136
+ let mut extractor = MoveExtractor::new();
137
+
138
+ match reader.read_game(&mut extractor) {
139
+ Ok(Some(_)) => Ok(extractor),
140
+ Ok(None) => Err(pyo3::exceptions::PyValueError::new_err(
141
+ "No game found in PGN",
142
+ )),
143
+ Err(err) => Err(pyo3::exceptions::PyValueError::new_err(format!(
144
+ "Parsing error: {}",
145
+ err
146
+ ))),
147
+ }
148
+ }
149
+
150
+ /// A Python module implemented in Rust.
151
+ #[pymodule]
152
+ fn rust_pgn_reader_python_binding(m: &Bound<'_, PyModule>) -> PyResult<()> {
153
+ m.add_function(wrap_pyfunction!(parse_moves, m)?)?;
154
+ Ok(())
155
+ }
@@ -0,0 +1,307 @@
1
+ import unittest
2
+ import rust_pgn_reader_python_binding
3
+
4
+
5
+ class TestPgnExtraction(unittest.TestCase):
6
+ def run_extractor(self, pgn_string):
7
+ extractor = rust_pgn_reader_python_binding.parse_moves(pgn_string)
8
+ return extractor
9
+
10
+ def test_short_pgn(self):
11
+ pgn_moves = "1. e4 {asdf} e5 2. Nf3 Nc6 3. Bb5 Nf6 4. O-O {hello} Bc5 5. d3 d6 6. h3 h6 7. c3 O-O 8. Be3 a6 9. Ba4 Bd7 10. Bxc5 dxc5 11. Bxc6 Bxc6 12. Nxe5 Bb5 13. Re1 Re8 14. c4 Rxe5 15. cxb5 axb5 16. Nc3 b4 17. Nd5 Nxd5 18. exd5 Rxe1+ 19. Qxe1 Qxd5 20. Qe3 b6 21. b3 c6 22. Qe2 b5 23. Rd1 Qd4 24. Qe7 Rxa2 25. Qe8+ Kh7 26. Qxf7 c4 27. Qf5+ Kh8 28. Qf8+ Kh7 29. Qf5+ Kh8 30. Qf8+ Kh7 31. Qf5+ Kh8 32. Qf8+ Kh7 1/2-1/2"
12
+ extractor = self.run_extractor(pgn_moves)
13
+
14
+ moves_reference = [
15
+ "e2e4",
16
+ "e7e5",
17
+ "g1f3",
18
+ "b8c6",
19
+ "f1b5",
20
+ "g8f6",
21
+ "e1g1",
22
+ "f8c5",
23
+ "d2d3",
24
+ "d7d6",
25
+ "h2h3",
26
+ "h7h6",
27
+ "c2c3",
28
+ "e8g8",
29
+ "c1e3",
30
+ "a7a6",
31
+ "b5a4",
32
+ "c8d7",
33
+ "e3c5",
34
+ "d6c5",
35
+ "a4c6",
36
+ "d7c6",
37
+ "f3e5",
38
+ "c6b5",
39
+ "f1e1",
40
+ "f8e8",
41
+ "c3c4",
42
+ "e8e5",
43
+ "c4b5",
44
+ "a6b5",
45
+ "b1c3",
46
+ "b5b4",
47
+ "c3d5",
48
+ "f6d5",
49
+ "e4d5",
50
+ "e5e1",
51
+ "d1e1",
52
+ "d8d5",
53
+ "e1e3",
54
+ "b7b6",
55
+ "b2b3",
56
+ "c7c6",
57
+ "e3e2",
58
+ "b6b5",
59
+ "a1d1",
60
+ "d5d4",
61
+ "e2e7",
62
+ "a8a2",
63
+ "e7e8",
64
+ "g8h7",
65
+ "e8f7",
66
+ "c5c4",
67
+ "f7f5",
68
+ "h7h8",
69
+ "f5f8",
70
+ "h8h7",
71
+ "f8f5",
72
+ "h7h8",
73
+ "f5f8",
74
+ "h8h7",
75
+ "f8f5",
76
+ "h7h8",
77
+ "f5f8",
78
+ "h8h7",
79
+ ]
80
+ comments_reference = ["asdf", "hello"]
81
+ valid_reference = True
82
+ evals_reference = []
83
+ clock_times_reference = []
84
+
85
+ self.assertTrue(extractor.moves == moves_reference)
86
+ self.assertTrue(extractor.comments == comments_reference)
87
+ self.assertTrue(extractor.valid_moves == valid_reference)
88
+ self.assertTrue(extractor.evals == evals_reference)
89
+ self.assertTrue(extractor.clock_times == clock_times_reference)
90
+
91
+ def test_full_pgn(self):
92
+ pgn_moves = """
93
+ [Event "Rated Classical game"]
94
+ [Site "https://lichess.org/lhy6ehiv"]
95
+ [White "goerch"]
96
+ [Black "niltonrosao001"]
97
+ [Result "0-1"]
98
+ [UTCDate "2013.06.30"]
99
+ [UTCTime "22:10:02"]
100
+ [WhiteElo "1702"]
101
+ [BlackElo "2011"]
102
+ [WhiteRatingDiff "-3"]
103
+ [BlackRatingDiff "+5"]
104
+ [ECO "A46"]
105
+ [Opening "Indian Game: Spielmann-Indian"]
106
+ [TimeControl "600+8"]
107
+ [Termination "Normal"]
108
+
109
+ 1. d4 Nf6 2. Nf3 c5 3. e3 b6 4. Nc3 e6 5. Bb5 a6 6. Bd3 Bb7 7. O-O b5 8. b3 d5 9. Bb2 Nbd7 10. a4 b4 11. Ne2 Bd6 12. c4 bxc3 13. Bxc3 O-O 14. Ng3 Rc8 15. dxc5 Nxc5 16. Nd4 Nxd3 17. Qxd3 Qb6 18. Rab1 Bb4 19. Nge2 Ne4 20. Rfc1 Nxc3 21. Nxc3 Rc7 22. Na2 Rfc8 23. Rc2 g6 24. Nxb4 Qxb4 25. Rbc1 Rxc2 26. Nxc2 Qc3 27. Qxc3 Rxc3 28. Kf1 d4 29. exd4 Be4 30. Ke1 Rxc2 31. Rxc2 Bxc2 32. Kd2 Bxb3 33. a5 Bd5 0-1
110
+
111
+ """
112
+ extractor = self.run_extractor(pgn_moves)
113
+
114
+ moves_reference = [
115
+ "d2d4",
116
+ "g8f6",
117
+ "g1f3",
118
+ "c7c5",
119
+ "e2e3",
120
+ "b7b6",
121
+ "b1c3",
122
+ "e7e6",
123
+ "f1b5",
124
+ "a7a6",
125
+ "b5d3",
126
+ "c8b7",
127
+ "e1g1",
128
+ "b6b5",
129
+ "b2b3",
130
+ "d7d5",
131
+ "c1b2",
132
+ "b8d7",
133
+ "a2a4",
134
+ "b5b4",
135
+ "c3e2",
136
+ "f8d6",
137
+ "c2c4",
138
+ "b4c3",
139
+ "b2c3",
140
+ "e8g8",
141
+ "e2g3",
142
+ "a8c8",
143
+ "d4c5",
144
+ "d7c5",
145
+ "f3d4",
146
+ "c5d3",
147
+ "d1d3",
148
+ "d8b6",
149
+ "a1b1",
150
+ "d6b4",
151
+ "g3e2",
152
+ "f6e4",
153
+ "f1c1",
154
+ "e4c3",
155
+ "e2c3",
156
+ "c8c7",
157
+ "c3a2",
158
+ "f8c8",
159
+ "c1c2",
160
+ "g7g6",
161
+ "a2b4",
162
+ "b6b4",
163
+ "b1c1",
164
+ "c7c2",
165
+ "d4c2",
166
+ "b4c3",
167
+ "d3c3",
168
+ "c8c3",
169
+ "g1f1",
170
+ "d5d4",
171
+ "e3d4",
172
+ "b7e4",
173
+ "f1e1",
174
+ "c3c2",
175
+ "c1c2",
176
+ "e4c2",
177
+ "e1d2",
178
+ "c2b3",
179
+ "a4a5",
180
+ "b3d5",
181
+ ]
182
+ comments_reference = []
183
+ valid_reference = True
184
+ evals_reference = []
185
+ clock_times_reference = []
186
+
187
+ self.assertTrue(extractor.moves == moves_reference)
188
+ self.assertTrue(extractor.comments == comments_reference)
189
+ self.assertTrue(extractor.valid_moves == valid_reference)
190
+ self.assertTrue(extractor.evals == evals_reference)
191
+ self.assertTrue(extractor.clock_times == clock_times_reference)
192
+
193
+ def test_full_pgn_annotated(self):
194
+ pgn_moves = """
195
+ 1. e4 { [%eval 0.17] [%clk 0:00:30] } 1... c5 { [%eval 0.19] [%clk 0:00:30] }
196
+ 2. Nf3 { [%eval 0.25] [%clk 0:00:29] } 2... Nc6 { [%eval 0.33] [%clk 0:00:30] }
197
+ 3. Bc4 { [%eval -0.13] [%clk 0:00:28] } 3... e6 { [%eval -0.04] [%clk 0:00:30] }
198
+ 4. c3 { [%eval -0.4] [%clk 0:00:27] } 4... b5? { [%eval 1.18] [%clk 0:00:30] }
199
+ 5. Bb3?! { [%eval 0.21] [%clk 0:00:26] } 5... c4 { [%eval 0.32] [%clk 0:00:29] }
200
+ 6. Bc2 { [%eval 0.2] [%clk 0:00:25] } 6... a5 { [%eval 0.6] [%clk 0:00:29] }
201
+ 7. d4 { [%eval 0.29] [%clk 0:00:23] } 7... cxd3 { [%eval 0.6] [%clk 0:00:27] }
202
+ 8. Qxd3 { [%eval 0.12] [%clk 0:00:22] } 8... Nf6 { [%eval 0.52] [%clk 0:00:26] }
203
+ 9. e5 { [%eval 0.39] [%clk 0:00:21] } 9... Nd5 { [%eval 0.45] [%clk 0:00:25] }
204
+ 10. Bg5?! { [%eval -0.44] [%clk 0:00:18] } 10... Qc7 { [%eval -0.12] [%clk 0:00:23] }
205
+ 11. Nbd2?? { [%eval -3.15] [%clk 0:00:14] } 11... h6 { [%eval -2.99] [%clk 0:00:23] }
206
+ 12. Bh4 { [%eval -3.0] [%clk 0:00:11] } 12... Ba6? { [%eval -0.12] [%clk 0:00:23] }
207
+ 13. b3?? { [%eval -4.14] [%clk 0:00:02] } 13... Nf4? { [%eval -2.73] [%clk 0:00:21] } 0-1
208
+ """
209
+ extractor = self.run_extractor(pgn_moves)
210
+
211
+ moves_reference = [
212
+ "e2e4",
213
+ "c7c5",
214
+ "g1f3",
215
+ "b8c6",
216
+ "f1c4",
217
+ "e7e6",
218
+ "c2c3",
219
+ "b7b5",
220
+ "c4b3",
221
+ "c5c4",
222
+ "b3c2",
223
+ "a7a5",
224
+ "d2d4",
225
+ "c4d3",
226
+ "d1d3",
227
+ "g8f6",
228
+ "e4e5",
229
+ "f6d5",
230
+ "c1g5",
231
+ "d8c7",
232
+ "b1d2",
233
+ "h7h6",
234
+ "g5h4",
235
+ "c8a6",
236
+ "b2b3",
237
+ "d5f4",
238
+ ]
239
+ comments_reference = [
240
+ "",
241
+ ] * 26
242
+ valid_reference = True
243
+ evals_reference = [
244
+ 0.17,
245
+ 0.19,
246
+ 0.25,
247
+ 0.33,
248
+ -0.13,
249
+ -0.04,
250
+ -0.4,
251
+ 1.18,
252
+ 0.21,
253
+ 0.32,
254
+ 0.2,
255
+ 0.6,
256
+ 0.29,
257
+ 0.6,
258
+ 0.12,
259
+ 0.52,
260
+ 0.39,
261
+ 0.45,
262
+ -0.44,
263
+ -0.12,
264
+ -3.15,
265
+ -2.99,
266
+ -3.0,
267
+ -0.12,
268
+ -4.14,
269
+ -2.73,
270
+ ]
271
+ clock_times_reference = [
272
+ (0, 0, 30),
273
+ (0, 0, 30),
274
+ (0, 0, 29),
275
+ (0, 0, 30),
276
+ (0, 0, 28),
277
+ (0, 0, 30),
278
+ (0, 0, 27),
279
+ (0, 0, 30),
280
+ (0, 0, 26),
281
+ (0, 0, 29),
282
+ (0, 0, 25),
283
+ (0, 0, 29),
284
+ (0, 0, 23),
285
+ (0, 0, 27),
286
+ (0, 0, 22),
287
+ (0, 0, 26),
288
+ (0, 0, 21),
289
+ (0, 0, 25),
290
+ (0, 0, 18),
291
+ (0, 0, 23),
292
+ (0, 0, 14),
293
+ (0, 0, 23),
294
+ (0, 0, 11),
295
+ (0, 0, 23),
296
+ (0, 0, 2),
297
+ (0, 0, 21),
298
+ ]
299
+ self.assertTrue(extractor.moves == moves_reference)
300
+ self.assertTrue(extractor.comments == comments_reference)
301
+ self.assertTrue(extractor.valid_moves == valid_reference)
302
+ self.assertTrue(extractor.evals == evals_reference)
303
+ self.assertTrue(extractor.clock_times == clock_times_reference)
304
+
305
+
306
+ if __name__ == "__main__":
307
+ unittest.main()
@@ -1,98 +0,0 @@
1
- use shakmaty::{uci::UciMove, Chess, Position};
2
-
3
- use pgn_reader::{BufferedReader, RawComment, SanPlus, Skip, Visitor};
4
- use pyo3::prelude::*;
5
- use std::io::Cursor;
6
-
7
- #[pyclass]
8
- /// A Visitor to extract SAN moves from PGN movetext
9
- struct MoveExtractor {
10
- #[pyo3(get)]
11
- moves: Vec<String>,
12
-
13
- #[pyo3(get)]
14
- valid_moves: bool,
15
-
16
- #[pyo3(get)]
17
- comments: Vec<String>,
18
-
19
- pos: Chess,
20
- }
21
-
22
- #[pymethods]
23
- impl MoveExtractor {
24
- #[new]
25
- fn new() -> MoveExtractor {
26
- MoveExtractor {
27
- moves: Vec::with_capacity(100),
28
- pos: Chess::default(),
29
- valid_moves: true,
30
- comments: Vec::with_capacity(100),
31
- }
32
- }
33
- }
34
-
35
- impl Visitor for MoveExtractor {
36
- type Result = bool;
37
-
38
- fn begin_game(&mut self) {
39
- self.moves.clear();
40
- self.pos = Chess::default();
41
- self.valid_moves = true;
42
- self.comments.clear();
43
- }
44
-
45
- fn san(&mut self, san_plus: SanPlus) {
46
- if self.valid_moves {
47
- match san_plus.san.to_move(&self.pos) {
48
- Ok(m) => {
49
- self.pos.play_unchecked(&m);
50
- let uci = UciMove::from_standard(&m);
51
- self.moves.push(uci.to_string());
52
- }
53
- Err(err) => {
54
- eprintln!("error in game: {} {}", err, san_plus);
55
- self.valid_moves = false;
56
- }
57
- }
58
- }
59
- }
60
-
61
- fn comment(&mut self, _comment: RawComment<'_>) {
62
- self.comments
63
- .push(String::from_utf8_lossy(_comment.as_bytes()).into_owned());
64
- }
65
-
66
- fn begin_variation(&mut self) -> Skip {
67
- Skip(true) // stay in the mainline
68
- }
69
-
70
- fn end_game(&mut self) -> Self::Result {
71
- self.valid_moves
72
- }
73
- }
74
-
75
- /// Parses PGN movetext and returns a list of SAN moves
76
- #[pyfunction]
77
- fn parse_moves(pgn: &str) -> PyResult<MoveExtractor> {
78
- let mut reader = BufferedReader::new(Cursor::new(pgn));
79
- let mut extractor = MoveExtractor::new();
80
-
81
- match reader.read_game(&mut extractor) {
82
- Ok(Some(_)) => Ok(extractor),
83
- Ok(None) => Err(pyo3::exceptions::PyValueError::new_err(
84
- "No game found in PGN",
85
- )),
86
- Err(err) => Err(pyo3::exceptions::PyValueError::new_err(format!(
87
- "Parsing error: {}",
88
- err
89
- ))),
90
- }
91
- }
92
-
93
- /// A Python module implemented in Rust.
94
- #[pymodule]
95
- fn rust_pgn_reader_python_binding(m: &Bound<'_, PyModule>) -> PyResult<()> {
96
- m.add_function(wrap_pyfunction!(parse_moves, m)?)?;
97
- Ok(())
98
- }
@@ -1,34 +0,0 @@
1
- import rust_pgn_reader_python_binding
2
-
3
- pgn_moves = "1. e4 {asdf} e5 2. Nf3 Nc6 3. Bb5 Nf6 4. O-O {hello} Bc5 5. d3 d6 6. h3 h6 7. c3 O-O 8. Be3 a6 9. Ba4 Bd7 10. Bxc5 dxc5 11. Bxc6 Bxc6 12. Nxe5 Bb5 13. Re1 Re8 14. c4 Rxe5 15. cxb5 axb5 16. Nc3 b4 17. Nd5 Nxd5 18. exd5 Rxe1+ 19. Qxe1 Qxd5 20. Qe3 b6 21. b3 c6 22. Qe2 b5 23. Rd1 Qd4 24. Qe7 Rxa2 25. Qe8+ Kh7 26. Qxf7 c4 27. Qf5+ Kh8 28. Qf8+ Kh7 29. Qf5+ Kh8 30. Qf8+ Kh7 31. Qf5+ Kh8 32. Qf8+ Kh7 1/2-1/2"
4
- extractor = rust_pgn_reader_python_binding.parse_moves(pgn_moves)
5
-
6
- print(extractor.moves)
7
- print(extractor.comments)
8
- print(extractor.valid_moves)
9
-
10
-
11
- pgn_full = """
12
- [Event "Rated Classical game"]
13
- [Site "https://lichess.org/lhy6ehiv"]
14
- [White "goerch"]
15
- [Black "niltonrosao001"]
16
- [Result "0-1"]
17
- [UTCDate "2013.06.30"]
18
- [UTCTime "22:10:02"]
19
- [WhiteElo "1702"]
20
- [BlackElo "2011"]
21
- [WhiteRatingDiff "-3"]
22
- [BlackRatingDiff "+5"]
23
- [ECO "A46"]
24
- [Opening "Indian Game: Spielmann-Indian"]
25
- [TimeControl "600+8"]
26
- [Termination "Normal"]
27
-
28
- 1. d4 Nf6 2. Nf3 c5 3. e3 b6 4. Nc3 e6 5. Bb5 a6 6. Bd3 Bb7 7. O-O b5 8. b3 d5 9. Bb2 Nbd7 10. a4 b4 11. Ne2 Bd6 12. c4 bxc3 13. Bxc3 O-O 14. Ng3 Rc8 15. dxc5 Nxc5 16. Nd4 Nxd3 17. Qxd3 Qb6 18. Rab1 Bb4 19. Nge2 Ne4 20. Rfc1 Nxc3 21. Nxc3 Rc7 22. Na2 Rfc8 23. Rc2 g6 24. Nxb4 Qxb4 25. Rbc1 Rxc2 26. Nxc2 Qc3 27. Qxc3 Rxc3 28. Kf1 d4 29. exd4 Be4 30. Ke1 Rxc2 31. Rxc2 Bxc2 32. Kd2 Bxb3 33. a5 Bd5 0-1
29
-
30
- """
31
- extractor = rust_pgn_reader_python_binding.parse_moves(pgn_full)
32
- print(extractor.moves)
33
- print(extractor.comments)
34
- print(extractor.valid_moves)