-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1972 lines (1715 loc) · 80.9 KB
/
app.py
File metadata and controls
1972 lines (1715 loc) · 80.9 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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import sys
import requests
# Ensure UTF-8 output on Windows
if os.name == 'nt': # Windows
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')
import base64
import time
import re
import nltk
import gc
import psutil
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
from nltk.tokenize import word_tokenize
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.decomposition import NMF
import numpy as np
from scipy.spatial.distance import cosine
import json
import warnings
import atexit
import shutil
import threading
import logging
from datetime import datetime, timedelta
from logging.handlers import RotatingFileHandler
from flask import Flask, render_template, send_from_directory, jsonify, Response, request, redirect
from dotenv import load_dotenv
# Database removed - using JSON file fallback only
# from database import AnalysisDatabase
from memory_manager import MemoryManager, get_memory_manager, log_memory, force_gc, monitor_threshold
# --- Configuration ---
load_dotenv() # Load environment variables from .env file (for local development)
app = Flask(__name__)
# Add cache-control headers to prevent frontend caching issues
@app.after_request
def after_request(response):
# Add cache-control headers to API and visualization routes
if request.path.startswith('/api/') or request.path in ['/visualization', '/analyze']:
response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate'
response.headers['Pragma'] = 'no-cache'
response.headers['Expires'] = '0'
return response
# Suppress warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
warnings.filterwarnings("ignore", category=FutureWarning)
# GitHub API configuration
GITHUB_TOKEN = os.getenv("GITHUB_PAT")
if not GITHUB_TOKEN:
print("WARNING: GITHUB_PAT environment variable not set. GitHub API calls will be severely rate-limited.")
# For unauthenticated requests, GitHub's rate limit is 60 requests per hour.
# Authenticated requests (with PAT) get 5,000 requests per hour.
# Code search has a specific limit of 30 requests per minute with PAT.
# If not set, the collection step might fail quickly.
HEADERS = {
"Authorization": f"token {GITHUB_TOKEN}" if GITHUB_TOKEN else "",
"Accept": "application/vnd.github.v3.text-match+json"
}
SEARCH_QUERY = "filename:claude.md"
BASE_URL = "https://api.github.com/search/code"
# NLTK downloads (run once on startup or when container builds)
def download_nltk_data():
"""Download required NLTK data with error handling"""
# Set NLTK data path for deployment environments
if os.name != 'nt':
nltk_data_dir = '/tmp/nltk_data'
os.makedirs(nltk_data_dir, exist_ok=True)
nltk.data.path.append(nltk_data_dir)
datasets = [
('corpora/stopwords', 'stopwords'),
('corpora/wordnet', 'wordnet'),
('tokenizers/punkt_tab', 'punkt_tab')
]
for path, name in datasets:
try:
nltk.data.find(path)
print(f"NLTK {name} already available")
except (LookupError, OSError):
try:
print(f"Downloading NLTK {name}...")
nltk.download(name, quiet=True, download_dir='/tmp/nltk_data' if os.name != 'nt' else None)
print(f"Successfully downloaded NLTK {name}")
except Exception as e:
print(f"Failed to download NLTK {name}: {e}")
# Download NLTK data on startup
download_nltk_data()
stop_words = set(stopwords.words('english'))
lemmatizer = WordNetLemmatizer()
# Global variable to store visualization HTML (cache it after first run)
# Paths for cached files and logs
# Use data/ directory (committed to repo) so historical data survives redeploys.
# On Render the repo is at /opt/render/project/src, so data/ lives there.
PERSISTENT_DATA_DIR = "/opt/render/project/src/data" if os.name != 'nt' else "data"
VIS_HTML_PATH = os.path.join(PERSISTENT_DATA_DIR, "lda_visualization.html") if os.name != 'nt' else "templates/lda_visualization.html"
ANALYSIS_CACHE_PATH = os.path.join(PERSISTENT_DATA_DIR, "last_analysis.json")
ANALYSIS_HISTORY_PATH = os.path.join(PERSISTENT_DATA_DIR, "analysis_history.json")
LOG_PATH = "/tmp/claude_analyzer.log" if os.name != 'nt' else "logs/claude_analyzer.log"
ANALYSIS_LOGS_DIR = "/tmp/analysis_logs/" if os.name != 'nt' else "logs/analysis_logs/"
TEMP_DIRS = ["/tmp", "/tmp/analysis_logs", PERSISTENT_DATA_DIR] if os.name != 'nt' else ["temp", "data", "logs", "logs/analysis_logs"]
# Analysis scheduling - runs daily at 3 AM GMT
ANALYSIS_TARGET_HOUR_GMT = 3 # 3 AM GMT
MAX_HISTORY_ENTRIES = 30 # Keep 30 days of history
last_analysis_thread = None
scheduler_thread = None
# Memory management functions
def get_memory_usage():
"""Get current memory usage in MB."""
try:
process = psutil.Process()
memory_info = process.memory_info()
return {
'rss_mb': round(memory_info.rss / 1024 / 1024, 1), # Resident Set Size
'vms_mb': round(memory_info.vms / 1024 / 1024, 1), # Virtual Memory Size
}
except:
return {'rss_mb': 0, 'vms_mb': 0}
def log_memory_usage(context="", force_gc=False):
"""Enhanced memory usage logging with advanced memory management."""
try:
# Use our new memory manager
memory_manager = get_memory_manager(logging.getLogger(__name__))
if force_gc:
force_gc(context, logging.getLogger(__name__))
else:
log_memory(context, logging.getLogger(__name__))
# Monitor memory threshold (600MB for emergency, 400MB for warning)
stats = memory_manager.get_memory_stats()
if stats['rss'] > 600:
logging.error(f"Critical memory usage: {stats['rss']}MB RSS - forcing cleanup")
memory_manager.cleanup_resources('emergency')
elif stats['rss'] > 400:
logging.warning(f"High memory usage detected: {stats['rss']}MB RSS")
monitor_threshold(400, context, logging.getLogger(__name__))
return {'rss_mb': stats['rss'], 'vms_mb': stats.get('vms', 0)}
except Exception as e:
logging.error(f"Error monitoring memory: {e}")
return {'rss_mb': 0, 'vms_mb': 0}
def cleanup_memory():
"""Enhanced memory cleanup using advanced memory management."""
try:
memory_manager = get_memory_manager(logging.getLogger(__name__))
# Perform comprehensive cleanup
memory_manager.cleanup_resources('manual-cleanup')
# Get final stats
stats = memory_manager.get_memory_stats()
return {'rss_mb': stats['rss'], 'vms_mb': stats.get('vms', 0)}
except Exception as e:
logging.error(f"Error during memory cleanup: {e}")
return get_memory_usage()
# Configure logging
def setup_logging():
"""Set up comprehensive logging with file rotation."""
try:
# Ensure log directory exists
log_dir = os.path.dirname(LOG_PATH)
if log_dir:
os.makedirs(log_dir, exist_ok=True)
# Create logger
logger = logging.getLogger()
logger.setLevel(logging.INFO)
# Create rotating file handler (10MB max, keep 5 backups)
file_handler = RotatingFileHandler(
LOG_PATH, maxBytes=10*1024*1024, backupCount=5
)
file_handler.setLevel(logging.INFO)
# Create console handler for development
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO)
# Create formatter
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
file_handler.setFormatter(formatter)
console_handler.setFormatter(formatter)
# Add handlers to logger
logger.addHandler(file_handler)
if os.name == 'nt': # Add console handler for local development
logger.addHandler(console_handler)
logging.info("Logging system initialized")
return True
except Exception as e:
print(f"Failed to setup logging: {e}")
return False
# Initialize logging
setup_logging()
# Database removed - using JSON file fallback only
db = None
logging.info("Using JSON file storage (no database)")
# Ensure cache directory exists
cache_dir = "/tmp" if os.name != 'nt' else "cache"
os.makedirs(cache_dir, exist_ok=True)
logging.info("Existing JSON data migration completed")
def create_analysis_logger(analysis_timestamp):
"""Create a dedicated logger for an individual analysis run."""
try:
# Ensure analysis logs directory exists
os.makedirs(ANALYSIS_LOGS_DIR, exist_ok=True)
# Create timestamp string for filename (safe for filesystem)
timestamp_str = analysis_timestamp.strftime("%Y-%m-%d_%H-%M-%S")
log_filename = f"analysis_{timestamp_str}.log"
log_filepath = os.path.join(ANALYSIS_LOGS_DIR, log_filename)
# Create dedicated logger for this analysis
logger_name = f"analysis_{timestamp_str}"
analysis_logger = logging.getLogger(logger_name)
analysis_logger.setLevel(logging.INFO)
# Remove any existing handlers
for handler in analysis_logger.handlers[:]:
analysis_logger.removeHandler(handler)
# Create file handler for this specific analysis
file_handler = logging.FileHandler(log_filepath)
file_handler.setLevel(logging.INFO)
# Create formatter
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
file_handler.setFormatter(formatter)
# Add handler to logger
analysis_logger.addHandler(file_handler)
analysis_logger.propagate = False # Don't propagate to root logger
return analysis_logger, log_filepath
except Exception as e:
logging.error(f"Failed to create analysis logger: {e}")
return None, None
# --- Cleanup Functions ---
def cleanup_temp_files():
"""Clean up temporary files created during analysis."""
try:
if os.path.exists(VIS_HTML_PATH):
os.remove(VIS_HTML_PATH)
print(f"Cleaned up visualization file: {VIS_HTML_PATH}")
except Exception as e:
print(f"Error during cleanup: {e}")
def cleanup_on_analysis_complete():
"""Clean up temporary data after successful visualization generation."""
# For now, we keep the visualization file since it's needed for viewing
# Could add more cleanup here if we create other temporary files
pass
# --- Persist data files to GitHub repo ---
GITHUB_REPO = "grzetich/analyzeclaudemd"
DATA_FILES_TO_PERSIST = [
("data/analysis_history.json", ANALYSIS_HISTORY_PATH),
("data/last_analysis.json", ANALYSIS_CACHE_PATH),
]
def persist_data_to_repo():
"""Push data files back to the GitHub repo so they survive Render rebuilds."""
if not GITHUB_TOKEN:
logging.warning("Cannot persist data to repo: no GITHUB_PAT configured")
return False
headers = {
"Authorization": f"token {GITHUB_TOKEN}",
"Accept": "application/vnd.github.v3+json",
}
any_updated = False
for repo_path, local_path in DATA_FILES_TO_PERSIST:
try:
if not os.path.exists(local_path):
logging.info(f"Skipping {repo_path}: local file does not exist")
continue
with open(local_path, 'r') as f:
content = f.read()
encoded = base64.b64encode(content.encode('utf-8')).decode('utf-8')
# Get the current file SHA (required by the API for updates)
url = f"https://api.github.com/repos/{GITHUB_REPO}/contents/{repo_path}"
resp = requests.get(url, headers=headers)
sha = None
if resp.status_code == 200:
sha = resp.json().get('sha')
# Create or update the file
payload = {
"message": f"Auto-update {repo_path} after analysis run",
"content": encoded,
"branch": "main",
}
if sha:
payload["sha"] = sha
put_resp = requests.put(url, headers=headers, json=payload)
if put_resp.status_code in (200, 201):
logging.info(f"Persisted {repo_path} to repo")
any_updated = True
else:
logging.error(f"Failed to persist {repo_path}: {put_resp.status_code} {put_resp.text[:200]}")
except Exception as e:
logging.error(f"Error persisting {repo_path} to repo: {e}")
return any_updated
def save_analysis_cache(success=False, message="", timestamp=None, files_collected=0, topics_discovered=0, topics_data=None, log_content=""):
"""Save analysis results to cache file and add to history."""
if timestamp is None:
timestamp = datetime.now().isoformat()
cache_data = {
'timestamp': timestamp,
'success': success,
'message': message,
'files_collected': files_collected,
'topics_discovered': topics_discovered,
'topics_data': topics_data # Store detailed topic information
}
try:
# Save to JSON (no database)
os.makedirs(os.path.dirname(ANALYSIS_CACHE_PATH), exist_ok=True)
with open(ANALYSIS_CACHE_PATH, 'w') as f:
json.dump(cache_data, f)
# Add to historical data (fallback)
if not db:
add_to_analysis_history(cache_data)
# Log the result
if success:
logging.info(f"Analysis completed successfully: {files_collected} files, {topics_discovered} topics")
else:
logging.error(f"Analysis failed: {message}")
except Exception as e:
logging.error(f"Error saving analysis cache: {e}")
print(f"Error saving analysis cache: {e}")
def load_analysis_cache():
"""Load analysis results from cache file."""
try:
if os.path.exists(ANALYSIS_CACHE_PATH):
with open(ANALYSIS_CACHE_PATH, 'r') as f:
return json.load(f)
except Exception as e:
logging.error(f"Error loading analysis cache: {e}")
print(f"Error loading analysis cache: {e}")
return None
def add_to_analysis_history(analysis_data):
"""Add analysis result to historical data."""
try:
history = load_analysis_history()
history.append(analysis_data)
# Trim history but protect successful entries from being evicted by failures.
# Keep at most MAX_HISTORY_ENTRIES successful runs plus the last 5 failed runs.
if len(history) > MAX_HISTORY_ENTRIES:
successful = [h for h in history if h.get('success')]
failed = [h for h in history if not h.get('success')]
# Keep the most recent successful entries (up to the cap)
successful = successful[-MAX_HISTORY_ENTRIES:]
# Keep only the last 5 failures for diagnostics
failed = failed[-5:]
# Merge and sort by timestamp
history = sorted(successful + failed, key=lambda h: h.get('timestamp', ''))
# Ensure history directory exists
os.makedirs(os.path.dirname(ANALYSIS_HISTORY_PATH), exist_ok=True)
with open(ANALYSIS_HISTORY_PATH, 'w') as f:
json.dump(history, f, indent=2)
except Exception as e:
logging.error(f"Error adding to analysis history: {e}")
print(f"Error adding to analysis history: {e}")
def load_analysis_history():
"""Load historical analysis results."""
try:
if db:
return db.get_analysis_history()
else:
# Fallback to JSON files
if os.path.exists(ANALYSIS_HISTORY_PATH):
with open(ANALYSIS_HISTORY_PATH, 'r') as f:
return json.load(f)
except Exception as e:
logging.error(f"Error loading analysis history: {e}")
print(f"Error loading analysis history: {e}")
return []
def get_analysis_stats():
"""Get analysis statistics from history."""
try:
history = load_analysis_history()
if not history:
return {
'total_analyses': 0,
'successful_analyses': 0,
'success_rate': 0,
'avg_files_collected': 0,
'last_30_days': []
}
successful = [h for h in history if h.get('success', False)]
return {
'total_analyses': len(history),
'successful_analyses': len(successful),
'success_rate': (len(successful) / len(history)) * 100 if history else 0,
'avg_files_collected': sum(h.get('files_collected', 0) for h in successful) / len(successful) if successful else 0,
'last_30_days': history[-30:] if len(history) > 30 else history
}
except Exception as e:
logging.error(f"Error calculating analysis stats: {e}")
return {'error': str(e)}
# --- Topic Evolution Analysis Functions ---
def calculate_topic_similarity(topic1, topic2, method='cosine'):
"""Calculate similarity between two topics using their word distributions."""
try:
# Extract word weights, ensuring same vocabulary
words1_dict = {word: weight for word, weight in zip(topic1['top_words'], topic1['weights'])}
words2_dict = {word: weight for word, weight in zip(topic2['top_words'], topic2['weights'])}
# Get union of vocabularies
all_words = set(words1_dict.keys()) | set(words2_dict.keys())
# Create aligned vectors
vector1 = np.array([words1_dict.get(word, 0.0) for word in all_words])
vector2 = np.array([words2_dict.get(word, 0.0) for word in all_words])
if method == 'cosine':
# Use 1 - cosine_distance to get cosine similarity
return 1 - cosine(vector1, vector2) if np.any(vector1) and np.any(vector2) else 0.0
elif method == 'jaccard':
# Jaccard similarity based on top N words overlap
top_n = min(10, len(topic1['top_words']), len(topic2['top_words']))
set1 = set(topic1['top_words'][:top_n])
set2 = set(topic2['top_words'][:top_n])
intersection = len(set1 & set2)
union = len(set1 | set2)
return intersection / union if union > 0 else 0.0
return 0.0
except Exception as e:
logging.error(f"Error calculating topic similarity: {e}")
return 0.0
def find_best_topic_matches(current_topics, historical_topics, threshold=0.3):
"""Find best matches between current and historical topics."""
matches = []
for current_idx, current_topic in enumerate(current_topics):
best_match = None
best_similarity = 0.0
for historical_idx, historical_topic in enumerate(historical_topics):
similarity = calculate_topic_similarity(current_topic, historical_topic)
if similarity > best_similarity and similarity >= threshold:
best_similarity = similarity
best_match = {
'historical_topic_id': historical_topic['topic_id'],
'similarity': similarity,
'historical_label': historical_topic['label']
}
matches.append({
'current_topic_id': current_idx,
'current_label': current_topic['label'],
'best_match': best_match,
'is_new_topic': best_match is None
})
return matches
def analyze_topic_evolution():
"""Analyze how topics have evolved over time across all historical runs."""
try:
history = load_analysis_history()
if len(history) < 2:
return {'error': 'Need at least 2 analysis runs to analyze evolution'}
# Filter successful runs with topics data
runs_with_topics = [h for h in history if h.get('success') and h.get('topics_data')]
if len(runs_with_topics) < 2:
return {'error': 'Need at least 2 successful runs with topic data'}
evolution_data = {
'total_runs_analyzed': len(runs_with_topics),
'timeline': [],
'topic_stability': {},
'new_topics_by_run': [],
'disappeared_topics': []
}
previous_topics = None
for i, run in enumerate(runs_with_topics):
current_topics = run['topics_data']
run_analysis = {
'timestamp': run['timestamp'],
'run_index': i,
'topics_count': len(current_topics),
'topics': current_topics
}
if previous_topics:
matches = find_best_topic_matches(current_topics, previous_topics)
run_analysis['topic_matches'] = matches
run_analysis['new_topics_count'] = sum(1 for m in matches if m['is_new_topic'])
# Track stability
for match in matches:
if not match['is_new_topic']:
topic_label = match['current_label']
if topic_label not in evolution_data['topic_stability']:
evolution_data['topic_stability'][topic_label] = []
evolution_data['topic_stability'][topic_label].append({
'run': i,
'similarity': match['best_match']['similarity']
})
evolution_data['timeline'].append(run_analysis)
previous_topics = current_topics
# Calculate overall stability metrics
stability_scores = {}
for topic_label, stability_history in evolution_data['topic_stability'].items():
avg_similarity = np.mean([s['similarity'] for s in stability_history])
appearances = len(stability_history) + 1 # +1 for first appearance
stability_scores[topic_label] = {
'avg_similarity': float(avg_similarity),
'appearances': appearances,
'consistency_score': float(avg_similarity * (appearances / len(runs_with_topics)))
}
evolution_data['stability_scores'] = stability_scores
return evolution_data
except Exception as e:
logging.error(f"Error analyzing topic evolution: {e}")
return {'error': str(e)}
def should_run_analysis():
"""Check if analysis should run based on daily 3 AM GMT schedule."""
cache = load_analysis_cache()
if not cache:
# Only run if it's currently around 3 AM GMT, not just because there's no cache
from datetime import timezone
now_gmt = datetime.now(timezone.utc)
current_hour = now_gmt.hour
# Run if it's between 3-4 AM GMT (1 hour window)
return current_hour == ANALYSIS_TARGET_HOUR_GMT
try:
from datetime import timezone
# Get the last run time
last_run = datetime.fromisoformat(cache['timestamp'])
if last_run.tzinfo is None:
last_run = last_run.replace(tzinfo=timezone.utc)
# Get current time in GMT
now_gmt = datetime.now(timezone.utc)
# Get today's 3 AM GMT
today_3am = now_gmt.replace(hour=ANALYSIS_TARGET_HOUR_GMT, minute=0, second=0, microsecond=0)
# If it's past 3 AM today and we haven't run since yesterday's 3 AM
if now_gmt >= today_3am:
yesterday_3am = today_3am - timedelta(days=1)
return last_run < yesterday_3am
else:
# If it's before 3 AM today, check if we need to run (should have run yesterday)
yesterday_3am = today_3am - timedelta(days=1)
return last_run < yesterday_3am
except Exception as e:
logging.error(f"Error checking analysis schedule: {e}")
return True
def time_until_next_analysis():
"""Calculate seconds until next scheduled analysis (3 AM GMT)."""
try:
from datetime import timezone
now_gmt = datetime.now(timezone.utc)
# Get next 3 AM GMT
next_3am = now_gmt.replace(hour=ANALYSIS_TARGET_HOUR_GMT, minute=0, second=0, microsecond=0)
# If we've passed 3 AM today, schedule for tomorrow
if now_gmt >= next_3am:
next_3am += timedelta(days=1)
return (next_3am - now_gmt).total_seconds()
except Exception as e:
logging.error(f"Error calculating next analysis time: {e}")
return 3600 # Default to 1 hour if error
def start_analysis_scheduler():
"""Start the background scheduler that runs analysis at 3 AM GMT daily."""
global scheduler_thread
def scheduler_worker():
"""Background scheduler that waits and runs analysis at the right time."""
while True:
try:
if should_run_analysis():
logging.info("Scheduled analysis time reached - starting analysis")
run_analysis_now()
# Sleep until next check (every hour)
time.sleep(3600) # Check every hour
except Exception as e:
logging.error(f"Error in analysis scheduler: {e}")
time.sleep(3600) # Continue checking after error
if not scheduler_thread or not scheduler_thread.is_alive():
scheduler_thread = threading.Thread(target=scheduler_worker, daemon=True)
scheduler_thread.start()
# Log next scheduled time
seconds_until = time_until_next_analysis()
next_run = datetime.now() + timedelta(seconds=seconds_until)
logging.info(f"Analysis scheduler started - next run scheduled for {next_run.strftime('%Y-%m-%d %H:%M:%S')} GMT")
def run_analysis_now():
"""Run analysis in background immediately."""
global last_analysis_thread
# Don't start if already running
if last_analysis_thread and last_analysis_thread.is_alive():
logging.info("Analysis already running, skipping new request")
return False
print("Starting analysis...")
logging.info("Starting on-demand analysis")
def analysis_worker():
analysis_start_time = datetime.now()
analysis_logger = None
log_filepath = None
try:
# Create individual analysis logger
analysis_logger, log_filepath = create_analysis_logger(analysis_start_time)
# Log to both main log and individual analysis log
logging.info("Starting scheduled analysis...")
if analysis_logger:
analysis_logger.info("=== ANALYSIS RUN STARTED ===")
analysis_logger.info(f"Analysis timestamp: {analysis_start_time.isoformat()}")
# Initial memory check
initial_memory = log_memory_usage("at analysis start")
if analysis_logger:
analysis_logger.info(f"Initial memory: RSS={initial_memory['rss_mb']}MB, VMS={initial_memory['vms_mb']}MB")
if not GITHUB_TOKEN:
error_msg = "GitHub PAT not configured"
logging.error(error_msg)
if analysis_logger:
analysis_logger.error(error_msg)
analysis_logger.info("=== ANALYSIS RUN FAILED ===")
save_analysis_cache(False, error_msg, files_collected=0, topics_discovered=0)
return
logging.info("Collecting claude.md files from GitHub...")
if analysis_logger:
analysis_logger.info("Starting GitHub file collection (max 500 files)...")
collected_documents = get_claude_md_files(SEARCH_QUERY, HEADERS, max_files=500)
# Memory check after collection
collection_memory = log_memory_usage("after GitHub collection")
if analysis_logger:
analysis_logger.info(f"Memory after collection: RSS={collection_memory['rss_mb']}MB, VMS={collection_memory['vms_mb']}MB")
if not collected_documents:
error_msg = "No claude.md files found"
logging.warning(error_msg)
if analysis_logger:
analysis_logger.warning(error_msg)
analysis_logger.info("=== ANALYSIS RUN COMPLETED (NO DATA) ===")
save_analysis_cache(False, error_msg, files_collected=0, topics_discovered=0)
return
num_files = len(collected_documents)
logging.info(f"Collected {num_files} files, starting LDA analysis...")
if analysis_logger:
analysis_logger.info(f"Successfully collected {num_files} claude.md files")
analysis_logger.info("Starting LDA topic modeling analysis...")
# Pre-LDA memory cleanup
pre_lda_memory = cleanup_memory()
if analysis_logger:
analysis_logger.info(f"Memory before LDA: RSS={pre_lda_memory['rss_mb']}MB")
success, topics_data = perform_lda_and_visualize(collected_documents, num_topics=5)
# Clean up memory aggressively after LDA
collected_documents.clear()
del collected_documents
post_lda_memory = cleanup_memory()
if analysis_logger:
analysis_logger.info(f"Memory after LDA cleanup: RSS={post_lda_memory['rss_mb']}MB")
if success:
success_msg = f"Analysis complete with {num_files} files"
logging.info(f"Scheduled analysis completed successfully with {num_files} files")
if analysis_logger:
analysis_logger.info("LDA analysis completed successfully")
analysis_logger.info(f"Topics discovered: 5")
analysis_logger.info(f"Visualization generated: {VIS_HTML_PATH}")
# Final memory report using enhanced memory manager
try:
memory_manager = get_memory_manager(analysis_logger)
final_report = memory_manager.log_final_report()
analysis_logger.info(f"Peak memory usage: {final_report['current']['rss']}MB RSS")
analysis_logger.info(f"Total GC collections: {final_report['gc_stats']['total_collections']}")
except Exception as mem_error:
analysis_logger.warning(f"Could not generate final memory report: {mem_error}")
analysis_logger.info("=== ANALYSIS RUN COMPLETED SUCCESSFULLY ===")
# Get log content for storage
log_content = ""
if log_filepath and os.path.exists(log_filepath):
try:
with open(log_filepath, 'r') as f:
log_content = f.read()
except Exception as e:
logging.warning(f"Could not read log content: {e}")
save_analysis_cache(True, success_msg, files_collected=num_files, topics_discovered=5, topics_data=topics_data, log_content=log_content)
cleanup_on_analysis_complete()
# Persist data files to GitHub repo so they survive Render rebuilds
try:
persist_data_to_repo()
except Exception as persist_error:
logging.warning(f"Could not persist data to repo: {persist_error}")
# Final comprehensive memory cleanup
try:
memory_manager = get_memory_manager(logging.getLogger(__name__))
memory_manager.cleanup_resources('analysis-complete')
except Exception as cleanup_error:
logging.warning(f"Final cleanup warning: {cleanup_error}")
print("Analysis completed successfully")
else:
error_msg = "Analysis failed during LDA processing"
logging.error(error_msg)
if analysis_logger:
analysis_logger.error("LDA processing failed")
analysis_logger.info("=== ANALYSIS RUN FAILED ===")
save_analysis_cache(False, error_msg, files_collected=num_files, topics_discovered=0)
print("Analysis failed")
except Exception as e:
error_msg = f"Analysis error: {str(e)}"
logging.error(f"Analysis error: {e}", exc_info=True)
if analysis_logger:
analysis_logger.error(f"Unexpected error during analysis: {e}", exc_info=True)
analysis_logger.info("=== ANALYSIS RUN FAILED WITH ERROR ===")
save_analysis_cache(False, error_msg, files_collected=0, topics_discovered=0)
print(f"Analysis error: {e}")
finally:
# Close individual analysis logger
if analysis_logger:
for handler in analysis_logger.handlers:
handler.close()
analysis_logger.removeHandler(handler)
# Log the final log file location to main log
if log_filepath:
logging.info(f"Individual analysis log saved to: {log_filepath}")
last_analysis_thread = threading.Thread(target=analysis_worker)
last_analysis_thread.daemon = True
last_analysis_thread.start()
return True
# Register cleanup function to run at exit
atexit.register(cleanup_temp_files)
# --- Helper Functions (from previous responses) ---
def get_claude_md_files(query, headers, max_files=100): # Limiting for MVP and rate limits
"""
Searches GitHub for claude.md files and retrieves their content.
Handles pagination and basic rate limit adherence with memory monitoring.
"""
all_file_contents = []
page = 1
per_page = 100 # Max per_page for code search is 100
print(f"Starting GitHub file collection (max {max_files} files)...")
logging.info(f"Starting GitHub file collection (max {max_files} files)...")
# Initial memory check
initial_memory = log_memory_usage("at file collection start")
while len(all_file_contents) < max_files:
params = {
"q": query,
"page": page,
"per_page": per_page,
"sort": "indexed",
"order": "desc"
}
response = requests.get(BASE_URL, headers=headers, params=params)
if response.status_code == 200:
data = response.json()
items = data.get("items", [])
if not items:
print("No more items found on GitHub search.")
break # No more items, exit loop
for item in items:
if len(all_file_contents) >= max_files:
break # Stop if max_files limit is reached
# Memory monitoring every 50 files (like viberater pattern)
if len(all_file_contents) % 50 == 0 and len(all_file_contents) > 0:
current_memory = log_memory_usage(f"after {len(all_file_contents)} files")
# Emergency cleanup if memory gets too high
if current_memory['rss_mb'] > 500:
logging.warning(f"High memory during collection: {current_memory['rss_mb']}MB - forcing cleanup")
gc.collect()
gc.collect()
download_url = item.get("download_url")
if download_url:
try:
file_response = requests.get(download_url, headers=headers)
if file_response.status_code == 200:
all_file_contents.append(file_response.text)
print(f" Downloaded via download_url: {item['repository']['full_name']}/{item['path']}")
else:
print(f" Failed to download {item['path']} from {item['repository']['full_name']}: {file_response.status_code}")
except Exception as e:
print(f" Error downloading {item['path']} from {item['repository']['full_name']}: {e}")
else:
# Fallback to GitHub Contents API for public repos
repo_full_name = item['repository']['full_name']
file_path = item['path']
contents_url = f"https://api.github.com/repos/{repo_full_name}/contents/{file_path}"
try:
contents_response = requests.get(contents_url, headers=headers)
if contents_response.status_code == 200:
contents_data = contents_response.json()
# Contents API returns a list when the path is a directory; skip those
if isinstance(contents_data, list):
print(f" Skipping directory listing for {file_path} in {repo_full_name}")
elif contents_data.get('encoding') == 'base64':
# Decode base64 content
content = base64.b64decode(contents_data['content']).decode('utf-8')
all_file_contents.append(content)
print(f" Downloaded via Contents API: {repo_full_name}/{file_path}")
else:
print(f" Unsupported encoding for {file_path} in {repo_full_name}: {contents_data.get('encoding')}")
elif contents_response.status_code == 404:
print(f" File not found or repo is private: {repo_full_name}/{file_path}")
elif contents_response.status_code == 403:
print(f" Access forbidden (likely private repo): {repo_full_name}/{file_path}")
else:
print(f" Contents API failed for {repo_full_name}/{file_path}: {contents_response.status_code}")
except Exception as e:
print(f" Error using Contents API for {repo_full_name}/{file_path}: {e}")
# Check if there are more pages
if "next" in response.links and len(all_file_contents) < max_files:
page += 1
# GitHub API best practice: wait a bit between requests to avoid hitting secondary limits
time.sleep(1) # Small delay
else:
break # No more pages
elif response.status_code == 403:
if "X-RateLimit-Remaining" in response.headers:
remaining = int(response.headers["X-RateLimit-Remaining"])
if remaining == 0:
reset_time = int(response.headers["X-RateLimit-Reset"])
current_time = int(time.time())
sleep_duration = max(0, reset_time - current_time + 5) # Add 5 seconds buffer
print(f"Rate limit hit ({remaining} requests remaining). Sleeping for {sleep_duration} seconds until {time.ctime(reset_time)}.")
time.sleep(sleep_duration)
continue # Try again after sleeping
else:
print(f"Error 403 (Forbidden) but {remaining} requests remaining. Check token permissions or other limits: {response.text}")
else:
print(f"Error 403 (Forbidden) without rate limit info. Check token or API details: {response.text}")
break # Break on persistent 403
else:
print(f"Error fetching data: {response.status_code} - {response.text}")
break
print(f"Finished collection. Total {len(all_file_contents)} files collected.")
logging.info(f"Finished collection. Total {len(all_file_contents)} files collected.")
# Final memory check after collection
final_memory = log_memory_usage("after file collection complete")
logging.info(f"Collection complete - final memory: RSS={final_memory['rss_mb']}MB")
return all_file_contents
def preprocess_text(text):
"""
Cleans and preprocesses text for LDA.
"""
text = text.lower()
text = re.sub(r'[^a-zA-Z\s]', '', text)
tokens = word_tokenize(text)
tokens = [word for word in tokens if word not in stop_words and len(word) > 2]
tokens = [lemmatizer.lemmatize(word) for word in tokens]
return tokens
def perform_lda_and_visualize(documents, num_topics=5):
"""
Performs NMF topic modeling on the given documents and creates an HTML visualization.
"""
if not documents:
print("No documents provided for NMF analysis.")
return False, None
# Memory check at start
start_memory = log_memory_usage("at NMF start")
# Preprocess documents into strings for TfidfVectorizer
processed_docs = []
for i, doc in enumerate(documents):
tokens = preprocess_text(doc)
if tokens:
processed_docs.append(' '.join(tokens))
if i % 100 == 0 and i > 0:
current_memory = log_memory_usage(f"after preprocessing {i} documents")
if current_memory['rss_mb'] > 800:
logging.warning(f"High memory during preprocessing: {current_memory['rss_mb']}MB")
gc.collect()
if not processed_docs:
print("No valid documents after preprocessing.")
return False, None
preprocess_memory = log_memory_usage("after preprocessing complete")
logging.info(f"Preprocessing complete - memory: RSS={preprocess_memory['rss_mb']}MB")