-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTextMind.py
More file actions
400 lines (384 loc) Β· 25.8 KB
/
TextMind.py
File metadata and controls
400 lines (384 loc) Β· 25.8 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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
#!/usr/bin/env python3
import sys, re, os, json
from collections import Counter
from pathlib import Path
from datetime import datetime
config = {
'positive_words': {'good', 'great', 'excellent', 'amazing', 'wonderful', 'fantastic', 'happy', 'joy', 'love', 'brilliant', 'perfect', 'beautiful', 'best', 'success', 'win', 'positive', 'hope', 'improve', 'benefit', 'advantage'},
'negative_words': {'bad', 'terrible', 'awful', 'horrible', 'poor', 'worst', 'hate', 'sad', 'anger', 'fail', 'problem', 'issue', 'wrong', 'error', 'difficult', 'crisis', 'threat', 'danger', 'risk', 'decline', 'worse', 'inferior'},
'stop_words': {'the', 'a', 'an', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for', 'of', 'with', 'by', 'from', 'as', 'is', 'was', 'are', 'were', 'been', 'be', 'have', 'has', 'had', 'do', 'does', 'did', 'will', 'would', 'could', 'should', 'may', 'might', 'can', 'this', 'that', 'these', 'those', 'i', 'you', 'he', 'she', 'it', 'we', 'they', 'what', 'which'},
'subjective_words': {'believe', 'think', 'feel', 'opinion', 'suggest', 'claim'}, 'objective_words': {'data', 'fact', 'study', 'research', 'evidence', 'result'},
'colors': {'red': '\033[91m', 'green': '\033[92m', 'yellow': '\033[93m', 'blue': '\033[94m', 'cyan': '\033[96m', 'white': '\033[97m', 'reset': '\033[0m', 'bold': '\033[1m'}
}
data = {'raw': '', 'sentences': [], 'words': [], 'clean_words': []}
results = {}
args = sys.argv[1:] if len(sys.argv) > 1 else []
def check_install(pkg_import, pkg_name=None):
pkg_name = pkg_name or pkg_import
try:
__import__(pkg_import)
return True
except ImportError:
print(f"{config['colors']['yellow']}Installing {pkg_name}...{config['colors']['reset']}")
os.system(f"{sys.executable} -m pip install {pkg_name} -q")
return True
def load_text(path):
if not Path(path).exists():
print(f"{config['colors']['red']}Error: File not found{config['colors']['reset']}")
sys.exit(1)
temp = Path(path).suffix.lower()
if temp in ['.txt', '.md']:
with open(path, 'r', encoding='utf-8') as file_handle:
return file_handle.read()
elif temp == '.pdf':
check_install('PyPDF2')
import PyPDF2
temp2 = ''
with open(path, 'rb') as file_handle:
temp3 = PyPDF2.PdfReader(file_handle)
for temp4 in range(len(temp3.pages)):
temp2 += temp3.pages[temp4].extract_text() + '\n'
# Format multi-column text
temp2 = re.sub(r'\n\s*\n\s*\n+', '\n\n', temp2)
temp2 = re.sub(r'[ \t]+', ' ', temp2)
temp2 = re.sub(r'(\w+)-\s*\n\s*(\w+)', r'\1\2', temp2)
return temp2
elif temp == '.docx':
check_install('docx', 'python-docx')
import docx
temp2 = docx.Document(path)
return '\n'.join([temp3.text for temp3 in temp2.paragraphs])
print(f"{config['colors']['red']}Unsupported format{config['colors']['reset']}")
sys.exit(1)
def preprocess():
data['sentences'] = [temp.strip() for temp in re.split(r'[.!?]+', data['raw']) if temp.strip()]
data['words'] = re.findall(r'\b[a-z]+\b', data['raw'].lower())
data['clean_words'] = [temp for temp in data['words'] if temp not in config['stop_words'] and len(temp) > 2]
def analyze():
# Word intelligence
temp = Counter(data['clean_words'])
results['word_freq'] = temp.most_common(10)
results['word_diversity'] = round(len(set(data['words'])) / len(data['words']) * 100, 2) if data['words'] else 0
results['rare_words'] = [w for w, f in temp.items() if f == 1 and len(w) > 6][:5]
# Sentence ranking and summaries
temp2 = []
for temp3 in data['sentences']:
temp4 = sum([temp.get(temp5.lower(), 0) for temp5 in re.findall(r'\b\w+\b', temp3)])
temp5 = data['sentences'].index(temp3) / len(data['sentences'])
temp4 = temp4 * (1 + (0.3 if temp5 < 0.2 or temp5 > 0.8 else 0))
temp2.append((temp3, temp4, data['sentences'].index(temp3)))
results['top_sentences'] = sorted(temp2, key=lambda t: t[1], reverse=True)[:5]
# Small summary (15%)
temp6 = max(2, int(len(data['sentences']) * 0.15))
temp7 = sorted(temp2, key=lambda t: t[1], reverse=True)[:temp6]
temp7 = sorted(temp7, key=lambda t: t[2])
results['summary_small'] = ' '.join([t[0] for t in temp7])
# Detailed summary (40%)
temp8 = max(4, int(len(data['sentences']) * 0.4))
temp9 = sorted(temp2, key=lambda t: t[1], reverse=True)[:temp8]
temp9 = sorted(temp9, key=lambda t: t[2])
temp10 = len(temp9) // 3
temp11 = []
for i in range(0, len(temp9), temp10):
temp11.append(' '.join([t[0] for t in temp9[i:i + temp10]]))
results['summary_detailed'] = '\n\n'.join(temp11[:3])
# Tone analysis
temp12 = {'positive': 0, 'negative': 0, 'neutral': 0}
temp13 = []
for temp14 in data['sentences']:
temp15 = temp14.lower()
temp16 = sum(1 for w in config['positive_words'] if w in temp15)
temp17 = sum(1 for w in config['negative_words'] if w in temp15)
if temp16 > temp17:
temp12['positive'] += 1
temp13.append(('positive', temp14))
elif temp17 > temp16:
temp12['negative'] += 1
temp13.append(('negative', temp14))
else:
temp12['neutral'] += 1
temp13.append(('neutral', temp14))
results['tone_counts'] = temp12
results['tone_sentences'] = temp13
# Bias analysis
temp18 = sum(1 for w in data['words'] if w in config['subjective_words'])
temp19 = sum(1 for w in data['words'] if w in config['objective_words'])
temp20 = temp18 + temp19
results['subjectivity'] = round(temp18 / temp20 * 100, 2) if temp20 > 0 else 0
results['objectivity'] = round(temp19 / temp20 * 100, 2) if temp20 > 0 else 0
# Semantic fingerprint & topic distribution
results['features'] = {
'lexical_density': len(data['clean_words']) / len(data['words']) if data['words'] else 0,
'avg_word_length': sum(len(w) for w in data['clean_words']) / len(data['clean_words']) if data['clean_words'] else 0,
'complexity': len(data['words']) / len(data['sentences']) if data['sentences'] else 0,
'vocabulary_richness': len(set(data['clean_words'])) / len(data['clean_words']) if data['clean_words'] else 0
}
# Topic distribution
temp21 = {'emotion': 0, 'action': 0, 'abstract': 0, 'technical': 0, 'social': 0}
temp22 = {'love', 'hate', 'happy', 'sad', 'fear', 'anger', 'joy', 'hope', 'feel'}
temp23 = {'do', 'make', 'create', 'build', 'move', 'act', 'run', 'work', 'start'}
temp24 = {'idea', 'concept', 'theory', 'principle', 'thought', 'belief', 'value'}
temp25 = {'data', 'system', 'process', 'function', 'method', 'algorithm', 'analysis'}
temp26 = {'people', 'society', 'community', 'group', 'team', 'family', 'human'}
for w in data['clean_words']:
if w in temp22: temp21['emotion'] += 1
elif w in temp23: temp21['action'] += 1
elif w in temp24: temp21['abstract'] += 1
elif w in temp25: temp21['technical'] += 1
elif w in temp26: temp21['social'] += 1
temp27 = sum(temp21.values())
results['topics'] = {k: round(v/temp27*100, 2) if temp27 > 0 else 0 for k, v in temp21.items()}
# Stats
results['stats'] = {
'sentences': len(data['sentences']),
'words': len(data['words']),
'unique': len(set(data['words'])),
'read_time': round(len(data['words']) / 300, 2),
'speak_time': round(len(data['words']) / 150, 2),
'avg_length': round(len(data['words']) / len(data['sentences']), 2) if data['sentences'] else 0
}
def keyword_context(keyword):
temp = []
temp2 = r'\b' + re.escape(keyword.lower()) + r'\b'
for temp3 in data['sentences']:
if re.search(temp2, temp3.lower()):
temp4 = re.sub(temp2, lambda m: f"{config['colors']['yellow']}{config['colors']['bold']}{temp3[m.start():m.end()]}{config['colors']['reset']}", temp3, flags=re.IGNORECASE)
temp.append(temp4)
return temp
def export_json():
temp = Path(args[0]).stem
temp2 = f"textmind_{temp}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
temp3 = results['tone_counts']
temp4 = sum(temp3.values())
temp5 = {
'metadata': {'source': args[0], 'generated': datetime.now().isoformat(), 'version': '1.0'},
'statistics': results['stats'],
'summaries': { 'small': results['summary_small'], 'detailed': results['summary_detailed'], 'top_sentences': [{'sentence': s, 'score': sc} for s, sc, _ in results['top_sentences']] },
'sentiment_analysis': { 'counts': results['tone_counts'], 'percentages': {k: round(v/temp4*100, 2) for k, v in temp3.items()} if temp4 > 0 else {}, 'all_sentences': [{'tone': t, 'sentence': s} for t, s in results['tone_sentences']], 'positive_sentences': [s for t, s in results['tone_sentences'] if t == 'positive'], 'negative_sentences': [s for t, s in results['tone_sentences'] if t == 'negative'], 'neutral_sentences': [s for t, s in results['tone_sentences'] if t == 'neutral'] },
'debate_analysis': { 'balance_positive_percent': round(temp3['positive']/(temp3['positive']+temp3['negative'])*100, 2) if (temp3['positive']+temp3['negative']) > 0 else 0, 'balance_negative_percent': round(temp3['negative']/(temp3['positive']+temp3['negative'])*100, 2) if (temp3['positive']+temp3['negative']) > 0 else 0, 'positive_arguments': [s for t, s in results['tone_sentences'] if t == 'positive'], 'negative_arguments': [s for t, s in results['tone_sentences'] if t == 'negative'] },
'word_intelligence': { 'top_keywords': [{'word': w, 'frequency': f} for w, f in results['word_freq']], 'word_diversity_percent': results['word_diversity'] },
'bias_analysis': { 'subjectivity_percent': results['subjectivity'], 'objectivity_percent': results['objectivity'], 'classification': 'subjective' if results['subjectivity'] > 60 else 'objective' if results['objectivity'] > 60 else 'balanced' },
'linguistic_features': results['features']
}
with open(temp2, 'w', encoding='utf-8') as file_handle:
json.dump(temp5, file_handle, indent=2, ensure_ascii=False)
pc(f"{config['colors']['green']}β
Exported: {temp2}{config['colors']['reset']}")
pc(f" Contains: {len(temp5)} sections with complete analysis", 'cyan')
def export_ml():
temp = Path(args[0]).stem
temp2 = f"textmind_ml_{temp}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
temp3 = results['tone_counts']
temp4 = sum(temp3.values())
# Calculate additional ML metrics
temp5 = results['topics']
temp6 = max(temp5.values()) if temp5 else 0
temp7 = max(temp5, key=temp5.get) if temp5 else 'general'
temp8 = {
'metadata': { 'document_id': temp, 'timestamp': datetime.now().isoformat(), 'source_file': args[0], 'processing_engine': 'TextMind v1.0' },
'feature_vectors': {
'linguistic_features': { 'lexical_density': round(results['features']['lexical_density'], 4), 'avg_word_length': round(results['features']['avg_word_length'], 4), 'avg_word_length_normalized': round(results['features']['avg_word_length'] / 15, 4), 'sentence_complexity': round(results['features']['complexity'], 4), 'sentence_complexity_normalized': round(min(results['features']['complexity'] / 50, 1.0), 4), 'vocabulary_richness': round(results['features']['vocabulary_richness'], 4), 'word_diversity': round(results['word_diversity'] / 100, 4) },
'sentiment_features': { 'positive_ratio': round(temp3['positive'] / temp4, 4) if temp4 > 0 else 0, 'negative_ratio': round(temp3['negative'] / temp4, 4) if temp4 > 0 else 0, 'neutral_ratio': round(temp3['neutral'] / temp4, 4) if temp4 > 0 else 0, 'sentiment_polarity': round((temp3['positive'] - temp3['negative']) / temp4, 4) if temp4 > 0 else 0, 'sentiment_strength': round((temp3['positive'] + temp3['negative']) / temp4, 4) if temp4 > 0 else 0 },
'bias_features': { 'subjectivity_score': round(results['subjectivity'] / 100, 4), 'objectivity_score': round(results['objectivity'] / 100, 4), 'bias_ratio': round(results['subjectivity'] / (results['objectivity'] + 1), 4) },
'topic_features': { 'emotion_score': round(temp5['emotion'] / 100, 4), 'action_score': round(temp5['action'] / 100, 4), 'abstract_score': round(temp5['abstract'] / 100, 4), 'technical_score': round(temp5['technical'] / 100, 4), 'social_score': round(temp5['social'] / 100, 4), 'dominant_topic_score': round(temp6 / 100, 4) },
'document_features': { 'length_words_normalized': round(min(results['stats']['words'] / 5000, 1.0), 4), 'length_sentences_normalized': round(min(results['stats']['sentences'] / 500, 1.0), 4), 'unique_word_ratio': round(results['stats']['unique'] / results['stats']['words'], 4) if results['stats']['words'] > 0 else 0, 'reading_difficulty': round(results['stats']['avg_length'] / 30, 4) },
'debate_features': { 'positive_argument_ratio': round(temp3['positive'] / (temp3['positive'] + temp3['negative']), 4) if (temp3['positive'] + temp3['negative']) > 0 else 0.5, 'negative_argument_ratio': round(temp3['negative'] / (temp3['positive'] + temp3['negative']), 4) if (temp3['positive'] + temp3['negative']) > 0 else 0.5, 'argumentative_balance': round(1 - abs(temp3['positive'] - temp3['negative']) / (temp3['positive'] + temp3['negative']), 4) if (temp3['positive'] + temp3['negative']) > 0 else 1.0 }
},
'categorical_labels': { 'sentiment_primary': 'positive' if temp3['positive'] > temp3['negative'] else 'negative' if temp3['negative'] > temp3['positive'] else 'neutral', 'sentiment_strength': 'strong' if max(temp3.values()) / temp4 > 0.6 else 'moderate' if max(temp3.values()) / temp4 > 0.4 else 'weak', 'writing_style': 'subjective' if results['subjectivity'] > 60 else 'objective' if results['objectivity'] > 60 else 'balanced', 'debate_position': 'pro' if temp3['positive'] > temp3['negative'] else 'con' if temp3['negative'] > temp3['positive'] else 'neutral', 'complexity_level': 'high' if results['features']['complexity'] > 25 else 'medium' if results['features']['complexity'] > 15 else 'low', 'dominant_topic': temp7, 'content_type': 'technical' if temp5['technical'] > 20 else 'emotional' if temp5['emotion'] > 20 else 'analytical' if temp5['abstract'] > 20 else 'general' },
'training_datasets': {
'text_samples': { 'summary_short': results['summary_small'], 'summary_long': results['summary_detailed'], 'all_sentences': data['sentences'] },
'labeled_sentences': { 'positive': [s for t, s in results['tone_sentences'] if t == 'positive'], 'negative': [s for t, s in results['tone_sentences'] if t == 'negative'], 'neutral': [s for t, s in results['tone_sentences'] if t == 'neutral'] },
'keywords': { 'top_10': [w for w, f in results['word_freq']], 'top_10_with_freq': [{'word': w, 'frequency': f, 'normalized_freq': round(f/results['stats']['words'], 4)} for w, f in results['word_freq']], 'rare_impactful': results.get('rare_words', []) }
},
'raw_statistics': { 'word_count': results['stats']['words'], 'sentence_count': results['stats']['sentences'], 'unique_word_count': results['stats']['unique'], 'avg_sentence_length': results['stats']['avg_length'], 'reading_time_minutes': results['stats']['read_time'], 'speaking_time_minutes': results['stats']['speak_time'], 'tone_distribution': results['tone_counts'], 'topic_distribution': results['topics'] },
'ml_usage_guide': {
'recommended_models': { 'classification': ['RandomForest', 'SVM', 'XGBoost', 'Neural Networks'], 'regression': ['Linear Regression', 'Ridge', 'Lasso', 'Gradient Boosting'], 'clustering': ['KMeans', 'DBSCAN', 'Hierarchical'], 'deep_learning': ['LSTM', 'BERT', 'Transformers'] },
'feature_engineering_tips': [ 'Use feature_vectors for direct ML input', 'Combine linguistic + sentiment features for classification', 'Use labeled_sentences for supervised learning', 'Topic features good for content categorization', 'Debate features useful for argument mining' ],
'use_cases': [ 'Sentiment Analysis: Use sentiment_features + labeled_sentences', 'Content Classification: Use topic_features + categorical_labels', 'Readability Scoring: Use linguistic_features + complexity_level', 'Debate Analysis: Use debate_features + debate_position', 'Style Transfer: Use writing_style + bias_features', 'Text Quality: Use vocabulary_richness + word_diversity' ],
'feature_vector_format': 'All features normalized to [0, 1] range for direct ML consumption',
'total_features': 27
}
}
with open(temp2, 'w', encoding='utf-8') as file_handle:
json.dump(temp8, file_handle, indent=2, ensure_ascii=False)
pc(f"\n{config['colors']['green']}β
ML DATASET EXPORTED SUCCESSFULLY{config['colors']['reset']}", 'green', True)
pc(f"{'='*60}", 'green')
pc(f"π File: {temp2}", 'cyan')
pc(f"π Features: {temp8['ml_usage_guide']['total_features']} normalized vectors", 'cyan')
pc(f"π·οΈ Labels: {len(temp8['categorical_labels'])} categorical + {len(temp8['feature_vectors'])} feature groups", 'cyan')
pc(f"π Training Samples: {len(data['sentences'])} sentences", 'cyan')
pc(f"{'='*60}", 'green')
pc("\nπ― QUICK STATS:", 'yellow', True)
pc(f" Sentiment: {temp8['categorical_labels']['sentiment_primary'].upper()} ({temp8['categorical_labels']['sentiment_strength']})", 'white')
pc(f" Style: {temp8['categorical_labels']['writing_style'].upper()}", 'white')
pc(f" Complexity: {temp8['categorical_labels']['complexity_level'].upper()}", 'white')
pc(f" Dominant Topic: {temp8['categorical_labels']['dominant_topic'].upper()}", 'white')
pc("\nπ‘ READY FOR:", 'yellow', True)
pc(" β scikit-learn (Classification, Regression, Clustering)", 'green')
pc(" β TensorFlow/PyTorch (Deep Learning)", 'green')
pc(" β XGBoost/LightGBM (Gradient Boosting)", 'green')
pc(" β BERT/Transformers (NLP Tasks)", 'green')
def pc(text, color='white', bold=False):
temp = config['colors'].get(color, config['colors']['white'])
temp2 = config['colors']['bold'] if bold else ''
print(f"{temp2}{temp}{text}{config['colors']['reset']}")
def show_help():
pc("\nββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ", 'cyan', True)
pc("β TEXTMIND - Text Intelligence System β", 'cyan', True)
pc("ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ", 'cyan', True)
print("\nUSAGE: python textmind.py <file> [options]")
print("\nFORMATS: .txt, .md, .pdf, .docx")
print("\nOPTIONS:")
print(" --summary Small summary (1 paragraph, default)")
print(" --summary-detailed Detailed summary (2-3 paragraphs)")
print(" --report Full intelligence report")
print(" --tone Sentiment analysis")
print(" --positive List positive sentences")
print(" --negative List negative sentences")
print(" --debate Pro vs con analysis")
print(" --context <word> Find keyword with highlighting")
print(" --export-json Export complete JSON report")
print(" --export-ml Export ML-ready dataset")
print(" --help Show this help")
def main():
if not args or '--help' in args:
show_help()
sys.exit(0)
temp = args[0]
pc("\nπ§ TextMind - Initializing...", 'cyan', True)
print(f"Loading: {temp}")
data['raw'] = load_text(temp)
preprocess()
if not data['sentences']:
pc("\nβ Error: No readable text found", 'red', True)
sys.exit(1)
analyze()
if '--export-json' in args:
export_json()
elif '--export-ml' in args:
export_ml()
elif '--context' in args:
try:
temp2 = args[args.index('--context') + 1]
temp3 = keyword_context(temp2)
pc(f"\n{'='*60}", 'cyan')
pc(f" KEYWORD CONTEXT: '{temp2}'", 'cyan', True)
pc(f"{'='*60}", 'cyan')
if temp3:
pc(f"\nFound {len(temp3)} occurrence(s):\n", 'cyan')
for i, sent in enumerate(temp3, 1):
print(f"{i}. {sent}\n")
else:
pc(f"\nβ Keyword '{temp2}' not found", 'red')
except (IndexError, ValueError):
pc("\nβ Error: Specify keyword after --context", 'red')
elif '--report' in args:
pc(f"\n{'='*32}", 'cyan', True)
pc("β TEXTMIND INTELLIGENCE REPORT β", 'cyan', True)
pc(f"{'='*32}", 'cyan', True)
pc("\nπ DOCUMENT STATISTICS", 'blue', True)
pc("β" * 70, 'blue')
print(f" π Total Sentences: {results['stats']['sentences']}")
print(f" π Total Words: {results['stats']['words']}")
print(f" π€ Unique Words: {results['stats']['unique']}")
print(f" π Word Diversity: {results['word_diversity']}%")
print(f" π Avg Sentence Length: {results['stats']['avg_length']} words")
print(f" β±οΈ Reading Time: {results['stats']['read_time']} minutes")
print(f" π£οΈ Speaking Time: {results['stats']['speak_time']} minutes")
pc("\nπ― SENTIMENT ANALYSIS", 'blue', True)
pc("β" * 70, 'blue')
temp = results['tone_counts']
temp2 = sum(temp.values())
for k, v in temp.items():
temp3 = round(v/temp2*100, 1) if temp2 > 0 else 0
temp4 = 'green' if k == 'positive' else 'red' if k == 'negative' else 'yellow'
temp5 = 'β' * int(temp3/5)
pc(f" {k.capitalize():10s} [{temp5:20s}] {v:3d} ({temp3}%)", temp4)
pc("\nπ‘ WORD INTELLIGENCE", 'blue', True)
pc("β" * 70, 'blue')
pc(" Top 10 Keywords:", 'cyan')
for i, (w, f) in enumerate(results['word_freq'], 1):
temp6 = 'β' * min(int(f/2), 20)
pc(f" {i:2d}. {w:15s} {temp6} {f}", 'white')
if results.get('rare_words'):
pc("\n π Hidden Gems (rare impactful words):", 'magenta')
for w in results['rare_words']:
pc(f" β’ {w}", 'magenta')
pc("\nπ DOCUMENT SUMMARY", 'blue', True)
pc("β" * 70, 'blue')
pc(" (Extractive summary - maintains narrative flow)\n", 'cyan')
print(f" {results['summary_small']}")
pc("\nπ BIAS ANALYSIS", 'blue', True)
pc("β" * 70, 'blue')
print(f" π Subjectivity: {results['subjectivity']}%")
print(f" π Objectivity: {results['objectivity']}%")
if results['subjectivity'] > 60:
pc(" β Writing Style: HIGHLY SUBJECTIVE", 'yellow')
elif results['objectivity'] > 60:
pc(" β Writing Style: HIGHLY OBJECTIVE", 'green')
else:
pc(" β Writing Style: BALANCED PERSPECTIVE", 'cyan')
pc("\n㪠SEMANTIC FINGERPRINT", 'blue', True)
pc("β" * 70, 'blue')
temp7 = results['features']
print(f" β’ Lexical Density: {temp7['lexical_density']:.2%} (meaningful word ratio)")
print(f" β’ Avg Word Length: {temp7['avg_word_length']:.1f} characters")
print(f" β’ Sentence Complexity: {temp7['complexity']:.1f} words/sentence")
print(f" β’ Vocabulary Richness: {temp7['vocabulary_richness']:.2%} (unique ratio)")
pc("\nπ TOPIC DISTRIBUTION", 'blue', True)
pc("β" * 70, 'blue')
temp8 = results['topics']
for k, v in sorted(temp8.items(), key=lambda x: x[1], reverse=True):
if v > 0:
temp9 = 'β' * int(v/5)
pc(f" {k.capitalize():12s} [{temp9:20s}] {v:.1f}%", 'cyan')
pc(f"\n{'='*70}", 'cyan', True)
elif '--summary-detailed' in args:
pc(f"\n{'='*60}", 'cyan')
pc(" DETAILED SUMMARY", 'cyan', True)
pc(f"{'='*60}", 'cyan')
print(f"\n{results['summary_detailed']}")
elif '--tone' in args:
pc(f"\n{'='*60}", 'cyan')
pc(" TONE ANALYSIS", 'cyan', True)
pc(f"{'='*60}", 'cyan')
for k, v in results['tone_counts'].items():
temp4 = 'green' if k == 'positive' else 'red' if k == 'negative' else 'yellow'
pc(f"{k.capitalize()}: {v} sentences", temp4)
elif '--positive' in args:
pc(f"\n{'='*60}", 'cyan')
pc(" POSITIVE SENTENCES", 'cyan', True)
pc(f"{'='*60}", 'cyan')
for tone, sent in results['tone_sentences']:
if tone == 'positive':
pc(f"β {sent}", 'green')
elif '--negative' in args:
pc(f"\n{'='*60}", 'cyan')
pc(" NEGATIVE SENTENCES", 'cyan', True)
pc(f"{'='*60}", 'cyan')
for tone, sent in results['tone_sentences']:
if tone == 'negative':
pc(f"β {sent}", 'red')
elif '--debate' in args:
pc(f"\n{'='*60}", 'cyan')
pc(" DEBATE ANALYSIS", 'cyan', True)
pc(f"{'='*60}", 'cyan')
temp5 = results['tone_counts']
temp6 = temp5['positive'] + temp5['negative']
if temp6 > 0:
pc(f"\nπ Balance: {round(temp5['positive']/temp6*100,1)}% Positive / {round(temp5['negative']/temp6*100,1)}% Negative", 'cyan', True)
temp7 = [s for t, s in results['tone_sentences'] if t == 'positive']
temp8 = [s for t, s in results['tone_sentences'] if t == 'negative']
pc(f"\nβ POSITIVE ARGUMENTS ({len(temp7)} total):", 'green', True)
for i, sent in enumerate(temp7, 1):
print(f" {i}. {sent}")
pc(f"\nβ NEGATIVE ARGUMENTS ({len(temp8)} total):", 'red', True)
for i, sent in enumerate(temp8, 1):
print(f" {i}. {sent}")
else:
pc(f"\n{'='*60}", 'cyan')
pc(" DOCUMENT SUMMARY", 'cyan', True)
pc(f"{'='*60}", 'cyan')
print(f"\n{results['summary_small']}")
pc("\nπ‘ Tip: Use --summary-detailed or --report for more", 'yellow')
if __name__ == '__main__':
main()