Kushalguptaiitb commited on
Commit
81533db
·
verified ·
1 Parent(s): 87ddef4

Upload test.txt

Browse files
Files changed (1) hide show
  1. test.txt +119 -0
test.txt ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ from typing import List, Dict
4
+
5
+ def merge_paragraph_chunks(input_json_path: str, output_dir: str, merge_count: int = 5):
6
+ """
7
+ Merges consecutive paragraph chunks of the same page from the input JSON file.
8
+
9
+ Args:
10
+ input_json_path (str): Path to the input JSON file.
11
+ output_dir (str): Directory where output JSON will be saved.
12
+ merge_count (int): Number of paragraphs to merge together.
13
+ """
14
+
15
+ # Read input JSON
16
+ with open(input_json_path, 'r', encoding='utf-8') as f:
17
+ data = json.load(f)
18
+
19
+ merged_result = []
20
+ temp_group: List[Dict] = []
21
+ current_page = None
22
+
23
+ def flush_group(group: List[Dict]):
24
+ """Helper to merge a group of paragraphs and return merged items."""
25
+ merged = []
26
+ for i in range(0, len(group), merge_count):
27
+ group_slice = group[i:i + merge_count]
28
+ merged_content = " ".join(item["content"].strip() for item in group_slice)
29
+ merged.append({
30
+ "type": "paragraph",
31
+ "content": merged_content.strip(),
32
+ "page": group_slice[0]["page"]
33
+ })
34
+ return merged
35
+
36
+ for item in data:
37
+ if item.get("type") == "paragraph":
38
+ page = item.get("page")
39
+ if current_page is None:
40
+ current_page = page
41
+
42
+ if page == current_page:
43
+ temp_group.append(item)
44
+ else:
45
+ # flush group from previous page
46
+ merged_result.extend(flush_group(temp_group))
47
+ temp_group = [item]
48
+ current_page = page
49
+ else:
50
+ # flush any existing group before adding a non-paragraph item
51
+ if temp_group:
52
+ merged_result.extend(flush_group(temp_group))
53
+ temp_group = []
54
+ current_page = None
55
+ merged_result.append(item)
56
+
57
+ # Final flush
58
+ if temp_group:
59
+ merged_result.extend(flush_group(temp_group))
60
+
61
+ # Save to output directory
62
+ os.makedirs(output_dir, exist_ok=True)
63
+ output_path = os.path.join(output_dir, 'merged_chunks.json')
64
+ with open(output_path, 'w', encoding='utf-8') as f:
65
+ json.dump(merged_result, f, indent=4)
66
+
67
+ print(f"✅ Merged chunks saved to: {output_path}")
68
+
69
+ ------------------------------------
70
+
71
+ import json
72
+ import os
73
+ from typing import List, Dict
74
+ from collections import defaultdict
75
+
76
+ def merge_one_chunk_per_page(input_json_path: str, output_dir: str):
77
+ """
78
+ Merge all paragraph chunks on the same page into one chunk per page.
79
+
80
+ Args:
81
+ input_json_path (str): Path to input JSON file.
82
+ output_dir (str): Directory to save the merged output JSON.
83
+ """
84
+
85
+ # Load input JSON
86
+ with open(input_json_path, 'r', encoding='utf-8') as f:
87
+ data = json.load(f)
88
+
89
+ # Dictionary to collect paragraphs by page
90
+ page_paragraphs = defaultdict(list)
91
+ other_elements = []
92
+
93
+ for item in data:
94
+ if item.get("type") == "paragraph":
95
+ page = item.get("page")
96
+ page_paragraphs[page].append(item["content"].strip())
97
+ else:
98
+ other_elements.append(item)
99
+
100
+ # Create one merged paragraph per page
101
+ merged_paragraphs = []
102
+ for page, paragraphs in sorted(page_paragraphs.items(), key=lambda x: int(x[0])):
103
+ merged_paragraphs.append({
104
+ "type": "paragraph",
105
+ "content": " ".join(paragraphs),
106
+ "page": page
107
+ })
108
+
109
+ # Combine with other elements (optional sorting logic can be added if needed)
110
+ final_output: List[Dict] = merged_paragraphs + other_elements
111
+
112
+ # Write to output
113
+ os.makedirs(output_dir, exist_ok=True)
114
+ output_path = os.path.join(output_dir, "merged_chunks.json")
115
+ with open(output_path, 'w', encoding='utf-8') as f:
116
+ json.dump(final_output, f, indent=4)
117
+
118
+ print(f"✅ One-chunk-per-page JSON saved at: {output_path}")
119
+