leejunyoung5819 handmade-dataset-creator
공개고품질 LLM 데이터셋 수제작을 위한 생산성 도구
| 1 | //! 열려 있는 데이터셋 문서와 되돌리기/다시하기 기록. |
| 2 | |
| 3 | use crate::model::{self, Conversation, Entry}; |
| 4 | use std::path::{Path, PathBuf}; |
| 5 | |
| 6 | /// 되돌릴 수 있는 편집 하나. |
| 7 | #[derive(Clone, Debug)] |
| 8 | pub enum Op { |
| 9 | /// 대화 하나의 내용을 바꿈. |
| 10 | Replace { index: usize, before: Box<Entry>, after: Box<Entry> }, |
| 11 | /// 대화 삽입. (최종 위치, 항목) — 위치 오름차순. |
| 12 | Insert { items: Vec<(usize, Entry)> }, |
| 13 | /// 대화 삭제. (원래 위치, 항목) — 위치 오름차순. |
| 14 | Remove { items: Vec<(usize, Entry)> }, |
| 15 | } |
| 16 | |
| 17 | impl Op { |
| 18 | fn apply(&self, entries: &mut Vec<Entry>) { |
| 19 | match self { |
| 20 | Op::Replace { index, after, .. } => entries[*index] = (**after).clone(), |
| 21 | Op::Insert { items } => { |
| 22 | for (i, e) in items { |
| 23 | entries.insert(*i, e.clone()); |
| 24 | } |
| 25 | } |
| 26 | Op::Remove { items } => { |
| 27 | for (i, _) in items.iter().rev() { |
| 28 | entries.remove(*i); |
| 29 | } |
| 30 | } |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | fn revert(&self, entries: &mut Vec<Entry>) { |
| 35 | match self { |
| 36 | Op::Replace { index, before, .. } => entries[*index] = (**before).clone(), |
| 37 | Op::Insert { items } => { |
| 38 | for (i, _) in items.iter().rev() { |
| 39 | entries.remove(*i); |
| 40 | } |
| 41 | } |
| 42 | Op::Remove { items } => { |
| 43 | for (i, e) in items { |
| 44 | entries.insert(*i, e.clone()); |
| 45 | } |
| 46 | } |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | /// 실행/되돌린 뒤 보여줄 대화 위치들. |
| 51 | pub fn affected(&self) -> Vec<usize> { |
| 52 | match self { |
| 53 | Op::Replace { index, .. } => vec![*index], |
| 54 | Op::Insert { items } | Op::Remove { items } => items.iter().map(|(i, _)| *i).collect(), |
| 55 | } |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | pub const HISTORY_LIMIT: usize = 200; |
| 60 | |
| 61 | pub struct Document { |
| 62 | pub entries: Vec<Entry>, |
| 63 | pub path: Option<PathBuf>, |
| 64 | undo: Vec<(u64, Op)>, |
| 65 | redo: Vec<(u64, Op)>, |
| 66 | next_id: u64, |
| 67 | saved_id: u64, |
| 68 | } |
| 69 | |
| 70 | impl Default for Document { |
| 71 | fn default() -> Self { |
| 72 | Document::new() |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | impl Document { |
| 77 | pub fn new() -> Self { |
| 78 | Document { entries: Vec::new(), path: None, undo: Vec::new(), redo: Vec::new(), next_id: 1, saved_id: 0 } |
| 79 | } |
| 80 | |
| 81 | pub fn open(path: &Path) -> std::io::Result<Self> { |
| 82 | let entries = model::load_entries(path)?; |
| 83 | Ok(Document { entries, path: Some(path.to_path_buf()), ..Document::new() }) |
| 84 | } |
| 85 | |
| 86 | pub fn save_to(&mut self, path: &Path) -> std::io::Result<()> { |
| 87 | model::save_entries(path, &self.entries)?; |
| 88 | self.path = Some(path.to_path_buf()); |
| 89 | self.saved_id = self.current_id(); |
| 90 | Ok(()) |
| 91 | } |
| 92 | |
| 93 | fn current_id(&self) -> u64 { |
| 94 | self.undo.last().map(|(id, _)| *id).unwrap_or(0) |
| 95 | } |
| 96 | |
| 97 | pub fn is_dirty(&self) -> bool { |
| 98 | self.current_id() != self.saved_id |
| 99 | } |
| 100 | |
| 101 | pub fn len(&self) -> usize { |
| 102 | self.entries.len() |
| 103 | } |
| 104 | |
| 105 | pub fn is_empty(&self) -> bool { |
| 106 | self.entries.is_empty() |
| 107 | } |
| 108 | |
| 109 | pub fn can_undo(&self) -> bool { |
| 110 | !self.undo.is_empty() |
| 111 | } |
| 112 | |
| 113 | pub fn can_redo(&self) -> bool { |
| 114 | !self.redo.is_empty() |
| 115 | } |
| 116 | |
| 117 | pub fn push(&mut self, op: Op) { |
| 118 | op.apply(&mut self.entries); |
| 119 | let id = self.next_id; |
| 120 | self.next_id += 1; |
| 121 | self.undo.push((id, op)); |
| 122 | if self.undo.len() > HISTORY_LIMIT { |
| 123 | self.undo.remove(0); |
| 124 | } |
| 125 | self.redo.clear(); |
| 126 | } |
| 127 | |
| 128 | pub fn undo(&mut self) -> Option<Vec<usize>> { |
| 129 | let (id, op) = self.undo.pop()?; |
| 130 | op.revert(&mut self.entries); |
| 131 | let affected = op.affected(); |
| 132 | self.redo.push((id, op)); |
| 133 | Some(affected) |
| 134 | } |
| 135 | |
| 136 | pub fn redo(&mut self) -> Option<Vec<usize>> { |
| 137 | let (id, op) = self.redo.pop()?; |
| 138 | op.apply(&mut self.entries); |
| 139 | let affected = op.affected(); |
| 140 | self.undo.push((id, op)); |
| 141 | Some(affected) |
| 142 | } |
| 143 | |
| 144 | /// `at` 위치에 새 대화를 만든다. |
| 145 | pub fn insert_conversation(&mut self, at: usize, conv: Conversation) { |
| 146 | let at = at.min(self.entries.len()); |
| 147 | self.push(Op::Insert { items: vec![(at, Entry::from_conv(conv))] }); |
| 148 | } |
| 149 | |
| 150 | pub fn remove_conversations(&mut self, indices: &[usize]) { |
| 151 | let mut idx: Vec<usize> = indices.iter().copied().filter(|&i| i < self.entries.len()).collect(); |
| 152 | idx.sort_unstable(); |
| 153 | idx.dedup(); |
| 154 | if idx.is_empty() { |
| 155 | return; |
| 156 | } |
| 157 | let items = idx.into_iter().map(|i| (i, self.entries[i].clone())).collect(); |
| 158 | self.push(Op::Remove { items }); |
| 159 | } |
| 160 | |
| 161 | /// 대화 하나를 수정한다. 클로저가 false를 돌려주면 아무 일도 기록하지 않는다. |
| 162 | /// 파싱에 실패한 대화는 수정할 수 없다(Err). |
| 163 | pub fn modify<R>(&mut self, index: usize, f: impl FnOnce(&mut Conversation) -> Option<R>) -> Result<Option<R>, String> { |
| 164 | let entry = self.entries.get_mut(index).ok_or("대화가 없습니다")?; |
| 165 | let mut conv = entry.conversation()?.clone(); |
| 166 | let before = entry.clone(); |
| 167 | let Some(r) = f(&mut conv) else { return Ok(None) }; |
| 168 | if Some(&conv) == before.parsed() { |
| 169 | return Ok(Some(r)); |
| 170 | } |
| 171 | self.push(Op::Replace { index, before: Box::new(before), after: Box::new(Entry::from_conv(conv)) }); |
| 172 | Ok(Some(r)) |
| 173 | } |
| 174 | } |