-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathextract_module.py
More file actions
201 lines (168 loc) · 5.85 KB
/
Copy pathextract_module.py
File metadata and controls
201 lines (168 loc) · 5.85 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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
#!/usr/bin/env python3
"""
Module Extraction Helper Script
Helps extract specific line ranges from ext.py into new modules
"""
import sys
import os
def extract_lines(source_file, start_line, end_line, output_file, class_name):
"""
Extract specific lines from source file and save to output file
Args:
source_file: Path to ext.py
start_line: Starting line number (1-indexed)
end_line: Ending line number (inclusive)
output_file: Path to output module file
class_name: Name of the class being extracted
"""
try:
with open(source_file, 'r', encoding='utf-8') as f:
lines = f.readlines()
# Extract the specified lines (convert to 0-indexed)
extracted_lines = lines[start_line-1:end_line]
# Create module header
header = f'''"""
{class_name} Module
Extracted from original ext.py
Auto-generated by extraction helper
"""
import os
import sys
import json
import re
import logging
import hashlib
import time
import sqlite3
import requests
from typing import Dict, List, Any, Optional, Tuple
from datetime import datetime
logger = logging.getLogger(__name__)
'''
# Combine header and extracted content
content = header + ''.join(extracted_lines)
# Write to output file
os.makedirs(os.path.dirname(output_file), exist_ok=True)
with open(output_file, 'w', encoding='utf-8') as f:
f.write(content)
print(f"✅ Extracted {end_line - start_line + 1} lines")
print(f" Source: {source_file} (lines {start_line}-{end_line})")
print(f" Output: {output_file}")
print(f" Class: {class_name}")
return True
except Exception as e:
print(f"❌ Error: {e}")
return False
def main():
"""Main function"""
# Check if ext.py exists
if not os.path.exists('ext.py'):
print("❌ ext.py not found in current directory!")
return
print("=" * 60)
print("🔧 Module Extraction Helper")
print("=" * 60)
print()
# Predefined extractions based on MIGRATION_GUIDE.md
extractions = [
{
'name': 'EnhancedCryptoUtils',
'start': 1626,
'end': 1962,
'output': 'core/crypto_utils.py',
'status': 'TODO'
},
{
'name': 'AdvancedBalanceChecker',
'start': 2060,
'end': 2375,
'output': 'core/balance_checker.py',
'status': 'TODO'
},
{
'name': 'EnhancedDatabaseManager',
'start': 2389,
'end': 2884,
'output': 'database/db_manager.py',
'status': 'TODO'
},
{
'name': 'EmailValidator',
'start': 203,
'end': 337,
'output': 'validators/email_validator.py',
'status': 'TODO'
},
{
'name': 'SMSAPIDetector',
'start': 1110,
'end': 1265,
'output': 'validators/sms_detector.py',
'status': 'TODO'
}
]
print("Available extractions:")
print()
for i, ext in enumerate(extractions, 1):
print(f"{i}. {ext['name']}")
print(f" Lines: {ext['start']}-{ext['end']} ({ext['end']-ext['start']+1} lines)")
print(f" Output: {ext['output']}")
print(f" Status: {ext['status']}")
print()
print("Commands:")
print(" extract <number> - Extract specific module")
print(" extract all - Extract all pending modules")
print(" quit - Exit")
print()
while True:
try:
command = input("Enter command: ").strip().lower()
if command == 'quit':
break
elif command == 'extract all':
print("\n🚀 Extracting all modules...")
for ext in extractions:
if ext['status'] == 'TODO':
print(f"\nExtracting {ext['name']}...")
success = extract_lines(
'ext.py',
ext['start'],
ext['end'],
ext['output'],
ext['name']
)
if success:
ext['status'] = 'DONE'
print("\n✅ All extractions complete!")
break
elif command.startswith('extract '):
try:
num = int(command.split()[1])
if 1 <= num <= len(extractions):
ext = extractions[num-1]
print(f"\nExtracting {ext['name']}...")
success = extract_lines(
'ext.py',
ext['start'],
ext['end'],
ext['output'],
ext['name']
)
if success:
ext['status'] = 'DONE'
print("\n✅ Extraction successful!")
print("⚠️ Note: You may need to manually adjust imports")
else:
print("❌ Invalid module number")
except (ValueError, IndexError):
print("❌ Invalid command. Use: extract <number>")
else:
print("❌ Unknown command. Use: extract <number>, extract all, or quit")
except KeyboardInterrupt:
print("\n\nInterrupted by user")
break
except Exception as e:
print(f"❌ Error: {e}")
print("\n👋 Done!")
if __name__ == '__main__':
main()