- Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcode_processor.py
More file actions
Latest commit
1073 lines (938 loc) · 43.2 KB
/
Copy pathcode_processor.py
File metadata and controls
1073 lines (938 loc) · 43.2 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
"""
מעבד קטעי קוד - זיהוי שפה, הדגשת תחביר ועיבוד
Code Processor - Language detection, syntax highlighting and processing
"""
importbase64
importio
importlogging
importre
frompathlibimportPath
fromtypingimportAny, Dict, List, Optional, Tuple, TypedDict
# Optional dependencies — מוגנים לשימוש בסביבת בדיקות/Docs
try:
importcairosvg# type: ignore
exceptException: # noqa: BLE001
cairosvg=None# type: ignore[assignment]
try:
importtextstat# type: ignore
exceptException: # noqa: BLE001
textstat=None# type: ignore[assignment]
# Language detection (optional)
try:
fromlangdetectimportDetectorFactory, detect# type: ignore
exceptException: # noqa: BLE001
classDetectorFactory: # type: ignore[no-redef]
seed=0
defdetect(_text: str) ->str: # type: ignore[no-redef]
return'text'
# Image processing (optional)
try:
fromPILimportImage, ImageDraw, ImageFont# type: ignore
exceptException: # noqa: BLE001
Image=None# type: ignore[assignment]
ImageDraw=None# type: ignore[assignment]
ImageFont=None# type: ignore[assignment]
# Syntax highlighting (optional)
try:
frompygmentsimporthighlight# type: ignore
frompygments.formattersimport (HtmlFormatter, ImageFormatter, TerminalFormatter) # type: ignore
frompygments.lexersimport (get_lexer_by_name, get_lexer_for_filename, guess_lexer) # type: ignore
frompygments.stylesimportget_style_by_name# type: ignore
frompygments.utilimportClassNotFound# type: ignore
exceptException: # noqa: BLE001
highlight=None# type: ignore[assignment]
HtmlFormatter=None# type: ignore[assignment]
ImageFormatter=None# type: ignore[assignment]
TerminalFormatter=None# type: ignore[assignment]
defget_lexer_by_name(_name: str): # type: ignore[no-redef]
raiseClassNotFound('pygments not available')
defget_lexer_for_filename(_fn: str): # type: ignore[no-redef]
raiseClassNotFound('pygments not available')
defguess_lexer(_code: str): # type: ignore[no-redef]
raiseClassNotFound('pygments not available')
defget_style_by_name(_style: str): # type: ignore[no-redef]
return'default'
classClassNotFound(Exception): # type: ignore[no-redef]
pass
fromconfigimportconfig
# cache_manager עלול להיות ממוקף ע"י טסטים: ספקי fallback
try:
fromcache_managerimportcache# type: ignore
exceptException: # pragma: no cover
cache=None# type: ignore[assignment]
try:
fromcache_managerimportcached# type: ignore
exceptException: # pragma: no cover
defcached(expire_seconds: int=300, key_prefix: str="default"): # type: ignore[no-redef]
def_decorator(func):
returnfunc
return_decorator
ifcacheisNone: # pragma: no cover
class_NullCache:
defdelete_pattern(self, *args, **kwargs):
return0
defset(self, *a, **k):
returnFalse
defget(self, *a, **k):
returnNone
cache=_NullCache() # type: ignore[assignment]
fromutilsimportnormalize_code
logger=logging.getLogger(__name__)
classHtmlHighlightingError:
def__init__(self, code: str):
self.code=code
# קביעת זרע לשחזור תוצאות זיהוי שפה
DetectorFactory.seed=0
classCodeProcessor:
"""מחלקה לעיבוד קטעי קוד"""
def__init__(self):
self.language_patterns=self._init_language_patterns()
self.common_extensions=self._init_extensions()
try:
self.style=get_style_by_name(config.HIGHLIGHT_THEME) ifget_style_by_nameelse'default'
exceptException:
self.style='default'
# הגדרת לוגר ייעודי לטיפול בשגיאות קוד
self.code_logger=logging.getLogger('code_handler')
ifnotself.code_logger.handlers:
handler=logging.StreamHandler() # שימוש ב-StreamHandler במקום FileHandler לסביבת פרודקשן
handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
self.code_logger.addHandler(handler)
self.code_logger.setLevel(logging.INFO)
defsanitize_code_blocks(self, text: str) ->str:
"""
מנקה וטיפול בקטעי קוד עם סימוני markdown (```)
מוודא שהקוד מפורמט כראוי ונקי משגיאות
"""
try:
ifnottextornotisinstance(text, str):
self.code_logger.warning("קלט לא תקין לסניטציה")
returntextor""
# בדיקה אם יש בלוקי קוד עם סימוני ```
if'```'intext:
self.code_logger.info("מזוהים בלוקי קוד עם סימוני ```")
# טיפול בבלוקי קוד עם שפה מוגדרת (```python, ```javascript וכו')
pattern=r'```(\w+)?\s*([\s\S]*?)```'
defreplace_code_block(match):
language_hint=match.group(1) or""
code_content=match.group(2) or""
# ניקוי הקוד מרווחים מיותרים
cleaned_code=code_content.strip()
# רישום הפעולה
self.code_logger.info(f"מעבד בלוק קוד: {language_hint}, אורך: {len(cleaned_code)}")
# החזרת הקוד הנקי בלבד (ללא סימוני ```)
returncleaned_code
# החלפת כל בלוקי הקוד
processed_text=re.sub(pattern, replace_code_block, text, flags=re.DOTALL)
# אם לא נמצאו התאמות עם שפה, נסה בלי שפה
ifprocessed_text==text:
simple_pattern=r'```([\s\S]*?)```'
processed_text=re.sub(simple_pattern, lambdam: m.group(1).strip(), text, flags=re.DOTALL)
self.code_logger.info("סניטציית קוד הושלמה בהצלחה")
returnprocessed_text
# אם אין בלוקי קוד, החזר את הטקסט כמו שהוא
returntext
exceptExceptionase:
self.code_logger.error(f"שגיאה בסניטציית קוד: {str(e)}")
# במקרה של שגיאה, החזר את הטקסט המקורי
returntext
defvalidate_code_input(self, code: str, filename: str=None, user_id: int=None) ->Tuple[bool, str, str]:
"""
מאמת קלט קוד ומחזיר תוקף, קוד מנוקה והודעת שגיאה אם יש
"""
try:
ifnotcodeornotisinstance(code, str):
ifuser_id:
fromutilsimportcode_error_logger
code_error_logger.log_validation_failure(user_id, 0, "קלט קוד לא תקין או ריק")
returnFalse, "", "קלט קוד לא תקין או ריק"
original_length=len(code)
# עבור קבצי Markdown נשמור את התוכן כמו שהוא (כולל בלוקי ``` מרובי שפות)
# כדי לא לפגוע במסמך מרובה-שפות.
is_markdown: bool=False
try:
ext=Path((filenameor"")).suffix.lower()
is_markdown=extin (".md", ".markdown")
exceptException:
is_markdown=False
# סניטציה ראשונית (דלג עבור Markdown), ואז נרמול להסרת תווים נסתרים
cleaned_code=codeifis_markdownelseself.sanitize_code_blocks(code)
try:
# בקבצי Markdown נשמר רווחי סוף שורה (Hard line breaks)
cleaned_code=normalize_code(
cleaned_code,
trim_trailing_whitespace=notis_markdown
)
exceptException:
# במקרה של כשל בנרמול, נמשיך עם הטקסט לאחר הסניטציה הבסיסית
pass
cleaned_length=len(cleaned_code)
# רישום הצלחת סניטציה
ifuser_idandoriginal_length!=cleaned_length:
fromutilsimportcode_error_logger
code_error_logger.log_sanitization_success(user_id, original_length, cleaned_length)
# בדיקות נוספות
iflen(cleaned_code.strip()) ==0:
ifuser_id:
fromutilsimportcode_error_logger
code_error_logger.log_validation_failure(user_id, original_length, "הקוד ריק לאחר עיבוד")
returnFalse, "", "הקוד ריק לאחר עיבוד"
# בדיקה אם הקוד ארוך מדי
iflen(cleaned_code) >50000: # 50KB limit
ifuser_id:
fromutilsimportcode_error_logger
code_error_logger.log_validation_failure(user_id, cleaned_length, "הקוד ארוך מדי (מעל 50KB)")
returnFalse, "", "הקוד ארוך מדי (מעל 50KB)"
# בדיקה לתווים לא חוקיים
try:
cleaned_code.encode('utf-8')
exceptUnicodeEncodeError:
ifuser_id:
fromutilsimportcode_error_logger
code_error_logger.log_validation_failure(user_id, cleaned_length, "הקוד מכיל תווים לא חוקיים")
returnFalse, "", "הקוד מכיל תווים לא חוקיים"
# רישום הצלחה
self.code_logger.info(f"אימות קוד הצליח, אורך: {len(cleaned_code)}")
ifuser_id:
fromutilsimportcode_error_logger
code_error_logger.log_code_activity(user_id, "validation_success", {
"original_length": original_length,
"cleaned_length": cleaned_length,
"filename": filename
})
returnTrue, cleaned_code, ""
exceptExceptionase:
error_msg=f"שגיאה באימות קוד: {str(e)}"
self.code_logger.error(error_msg)
ifuser_id:
fromutilsimportcode_error_logger
code_error_logger.log_code_processing_error(user_id, "validation_exception", str(e))
returnFalse, "", error_msg
def_init_language_patterns(self) ->Dict[str, List[str]]:
"""אתחול דפוסי זיהוי שפות תכנות"""
return {
'python': [
r'\bdef\s+\w+\s*\(',
r'\bimport\s+\w+',
r'\bfrom\s+\w+\s+import',
r'\bclass\s+\w+\s*\(',
r'\bif\s+__name__\s*==\s*["\']__main__["\']',
r'\bprint\s*\(',
r'\belif\b',
r'\btry\s*:',
r'\bexcept\b',
r'#.*$'
],
'javascript': [
r'\bfunction\s+\w+\s*\(',
r'\bvar\s+\w+',
r'\blet\s+\w+',
r'\bconst\s+\w+',
r'\bconsole\.log\s*\(',
r'\b=>\s*{',
r'\brequire\s*\(',
r'\bexport\s+',
r'//.*$',
r'/\*.*?\*/'
],
'java': [
r'\bpublic\s+class\s+\w+',
r'\bpublic\s+static\s+void\s+main',
r'\bSystem\.out\.println\s*\(',
r'\bprivate\s+\w+',
r'\bprotected\s+\w+',
r'\bimport\s+java\.',
r'\b@\w+',
r'\bthrows\s+\w+'
],
'cpp': [
r'#include\s*<.*>',
r'\bstd::\w+',
r'\busing\s+namespace\s+std',
r'\bint\s+main\s*\(',
r'\bcout\s*<<',
r'\bcin\s*>>',
r'\bclass\s+\w+\s*{',
r'\btemplate\s*<'
],
'c': [
r'#include\s*<.*\.h>',
r'\bint\s+main\s*\(',
r'\bprintf\s*\(',
r'\bscanf\s*\(',
r'\bmalloc\s*\(',
r'\bfree\s*\(',
r'\bstruct\s+\w+\s*{',
r'\btypedef\s+'
],
'php': [
r'<\?php',
r'\$\w+',
r'\becho\s+',
r'\bprint\s+',
r'\bfunction\s+\w+\s*\(',
r'\bclass\s+\w+\s*{',
r'\b->\w+',
r'\brequire_once\s*\('
],
'html': [
r'<!DOCTYPE\s+html>',
r'<html.*?>',
r'<head.*?>',
r'<body.*?>',
r'<div.*?>',
r'<p.*?>',
r'<script.*?>',
r'<style.*?>'
],
'css': [
r'\w+\s*{[^}]*}',
r'@media\s+',
r'@import\s+',
r'@font-face\s*{',
r':\s*\w+\s*;',
r'#\w+\s*{',
r'\.\w+\s*{'
],
'sql': [
r'\bSELECT\s+',
r'\bFROM\s+\w+',
r'\bWHERE\s+',
r'\bINSERT\s+INTO',
r'\bUPDATE\s+\w+',
r'\bDELETE\s+FROM',
r'\bCREATE\s+TABLE',
r'\bALTER\s+TABLE'
],
'bash': [
r'#!/bin/bash',
r'#!/bin/sh',
r'#!/usr/bin/env\s+bash',
r'#!/usr/bin/env\s+sh',
r'\becho\s+',
r'\bif\s*\[.*\]',
r'\bfor\s+\w+\s+in',
r'\bwhile\s*\[.*\]',
r'\$\{\w+\}',
r'\$\w+'
],
'json': [
r'^\s*{',
r'^\s*\[',
r'"\w+"\s*:',
r':\s*"[^"]*"',
r':\s*\d+',
r':\s*true|false|null'
],
'xml': [
r'<\?xml\s+version',
r'<\w+.*?/>',
r'<\w+.*?>.*?</\w+>',
r'<!--.*?-->',
r'\sxmlns\s*='
],
'yaml': [
r'^\s*\w+\s*:',
r'^\s*-\s+\w+',
r'---\s*$',
r'^\s*#.*$'
],
'markdown': [
r'^#.*$',
r'^\*.*\*$',
r'^```.*$',
r'^\[.*\]\(.*\)$',
r'^!\[.*\]\(.*\)$'
]
}
def_init_extensions(self) ->Dict[str, str]:
"""מיפוי סיומות קבצים לשפות"""
return {
'.py': 'python',
'.js': 'javascript',
'.jsx': 'javascript',
'.ts': 'typescript',
'.tsx': 'typescript',
'.java': 'java',
'.cpp': 'cpp',
'.cxx': 'cpp',
'.cc': 'cpp',
'.c': 'c',
'.h': 'c',
'.hpp': 'cpp',
'.php': 'php',
'.html': 'html',
'.htm': 'html',
'.css': 'css',
'.scss': 'scss',
'.sass': 'sass',
'.less': 'less',
'.sql': 'sql',
'.sh': 'bash',
'.bash': 'bash',
'.zsh': 'bash',
'.fish': 'fish',
'.ps1': 'powershell',
'.json': 'json',
'.xml': 'xml',
'.yaml': 'yaml',
'.yml': 'yaml',
'.md': 'markdown',
'.rst': 'rst',
'.go': 'go',
'.rs': 'rust',
'.rb': 'ruby',
'.pl': 'perl',
'.r': 'r',
'.m': 'matlab',
'.swift': 'swift',
'.kt': 'kotlin',
'.scala': 'scala',
'.cs': 'csharp',
'.vb': 'vbnet',
'.lua': 'lua',
'.dart': 'dart',
'.dockerfile': 'dockerfile',
'.tf': 'hcl',
'.hcl': 'hcl'
}
defdetect_language(self, code: str, filename: str=None) ->str:
"""זיהוי שפת התכנות של הקוד"""
# סניטציה ראשונית של הקוד
try:
sanitized_code=self.sanitize_code_blocks(code)
self.code_logger.info(f"קוד סונטז לזיהוי שפה, אורך מקורי: {len(code)}, אורך מנוקה: {len(sanitized_code)}")
exceptExceptionase:
self.code_logger.error(f"שגיאה בסניטציה לזיהוי שפה: {e}")
sanitized_code=code
# בדיקה ראשונה - לפי סיומת הקובץ
iffilename:
ext=Path(filename).suffix.lower()
ifextinself.common_extensions:
detected=self.common_extensions[ext]
logger.info(f"זוהתה שפה לפי סיומת: {detected}")
returndetected
# בדיקה שנייה - לפי דפוסי קוד
language_scores= {}
forlanguage, patternsinself.language_patterns.items():
score=0
forpatterninpatterns:
matches=re.findall(pattern, sanitized_code, re.MULTILINE|re.IGNORECASE)
score+=len(matches)
ifscore>0:
language_scores[language] =score
iflanguage_scores:
detected=max(language_scores, key=language_scores.get)
logger.info(f"זוהתה שפה לפי דפוסים: {detected} (ניקוד: {language_scores[detected]})")
returndetected
# בדיקה שלישית - באמצעות Pygments
try:
ifnotguess_lexer:
raiseClassNotFound('pygments guess_lexer unavailable')
lexer=guess_lexer(sanitized_code)
ifnotlexer:
raiseClassNotFound('no lexer returned')
detected=getattr(lexer, 'name', 'text').lower()
# נרמול שמות שפות
if'python'indetected:
return'python'
elif'javascript'indetectedor'js'indetected:
return'javascript'
elif'java'indetected:
return'java'
elif'html'indetected:
return'html'
elif'css'indetected:
return'css'
elif'sql'indetected:
return'sql'
elif'bash'indetectedor'shell'indetected:
return'bash'
logger.info(f"זוהתה שפה באמצעות Pygments: {detected}")
returndetected
exceptClassNotFound:
logger.warning("לא הצלחתי לזהות שפה באמצעות Pygments")
# בדיקה רביעית - ניתוח כללי של הטקסט
detected=self._analyze_code_structure(sanitized_code)
ifdetected!='text':
logger.info(f"זוהתה שפה לפי מבנה: {detected}")
returndetected
# ברירת מחדל
logger.info("לא הצלחתי לזהות שפה, משתמש ב-text")
return'text'
def_analyze_code_structure(self, code: str) ->str:
"""ניתוח מבנה הקוד לזיהוי שפה"""
# ספירת סימנים מיוחדים
braces=code.count('{') +code.count('}')
brackets=code.count('[') +code.count(']')
parens=code.count('(') +code.count(')')
semicolons=code.count(';')
colons=code.count(':')
indentation_lines=len([lineforlineincode.split('\n') ifline.startswith(' ') orline.startswith('\t')])
total_lines=len(code.split('\n'))
# חישוב יחסים
iftotal_lines>0:
brace_ratio=braces/total_lines
semicolon_ratio=semicolons/total_lines
indent_ratio=indentation_lines/total_lines
# כללי זיהוי
ifindent_ratio>0.3andbrace_ratio<0.1:
return'python'
elifbrace_ratio>0.2andsemicolon_ratio>0.2:
return'javascript'
elif'<'incodeand'>'incodeand'html'incode.lower():
return'html'
elifcode.strip().startswith('{') orcode.strip().startswith('['):
return'json'
return'text'
defhighlight_code(self, code: str, programming_language: str, output_format: str='html') ->str:
"""עטיפת הדגשת תחביר עם ניהול cache רגיש לסביבת runtime."""
# תנאים מוקדמים מהירים שאינם צריכים cache
ifnotcodeorlen(code.strip()) <10:
ifoutput_format=='html':
returnf"<code>{code}</code>"
returncode
ifoutput_format=='terminal'and (TerminalFormatterisNoneorhighlightisNone):
returncode
# לכלול את זמינות הפורמטור במפתח ה-cache כדי למנוע התנגשויות בין ריצות שונות
runtime_key=f"term_avail={bool(TerminalFormatterandhighlight)}"ifoutput_format=='terminal'elsef"html_style={self.style}"
returnself._highlight_code_cached(code, programming_language, output_format, runtime_key)
@cached(expire_seconds=1800, key_prefix="syntax_highlight") # cache ל-30 דקות
def_highlight_code_cached(self, code: str, programming_language: str, output_format: str, runtime_key: str) ->str:
try:
# בחירת lexer מתאים
lexer=None
try:
ifprogramming_languageandprogramming_language!='text':
lexer=get_lexer_by_name(programming_language)
exceptClassNotFound:
# lexer לשפה המבוקשת לא נמצא — ננסה לנחש
lexer=None
exceptExceptionase:
logger.warning(f"lexer lookup error for '{programming_language}': {e}")
lexer=None
ifnotlexer:
try:
lexer=guess_lexer(code) ifguess_lexerelseNone
exceptClassNotFound:
lexer=None
exceptExceptionase:
logger.warning(f"guess_lexer error: {e}")
lexer=None
ifnotlexer:
try:
lexer=get_lexer_by_name('text')
exceptException:
# עקביות: ב-HTML מחזירים עטיפה, ב-terminal טקסט גולמי
returnf"<code>{code}</code>"ifoutput_format=='html'elsecode
# בחירת formatter
ifoutput_format=='html'andHtmlFormatterisnotNone:
formatter=HtmlFormatter(
style=self.style,
noclasses=True,
nowrap=True,
linenos=False
)
elifoutput_format=='terminal'andTerminalFormatterisnotNone:
formatter=TerminalFormatter()
else:
returnf"<code>{code}</code>"ifoutput_format=='html'elsecode
# ביצוע highlighting
ifhighlightisNone:
returnf"<code>{code}</code>"ifoutput_format=='html'elsecode
highlighted=highlight(code, lexer, formatter)
# ניקוי HTML אם נדרש
ifoutput_format=='html':
ifnotisinstance(highlighted, str):
returnf"<code>{code}</code>"
highlighted=self._clean_html_for_telegram(highlighted)
returnhighlighted
exceptExceptionase:
logger.error(f"שגיאה בהדגשת תחביר: {e}")
# במסלול שגיאה כללי שמור על עקביות HTML: עטיפה ב-<code>...</code>
returnf"<code>{code}</code>"ifoutput_format=='html'elsecode
def_clean_html_for_telegram(self, html_code: str) ->str:
"""ניקוי HTML לתאימות עם Telegram"""
try:
# הסרת attributes מיותרים
importre
# שמירה על tags בסיסיים בלבד
allowed_tags= ['b', 'i', 'u', 'code', 'pre', 'em', 'strong']
# הסרת style attributes
html_code=re.sub(r'\s+style="[^"]*"', '', html_code)
# הסרת class attributes
html_code=re.sub(r'\s+class="[^"]*"', '', html_code)
# החלפת span tags ב-code tags
html_code=re.sub(r'<span[^>]*>', '<code>', html_code)
html_code=re.sub(r'</span>', '</code>', html_code)
# ודא שעטפנו ב-<code> גם אם לא היו span
if'<code>'notinhtml_code:
html_code=f"<code>{html_code}</code>"
returnhtml_code
exceptExceptionase:
logger.error(f"שגיאה בניקוי HTML: {e}")
returnhtml_code
defcreate_code_image(self, code: str, programming_language: str,
output_format: str='html') ->Optional[bytes]:
"""יצירת תמונה של קוד עם הדגשת תחביר"""
try:
width: int=1200
font_size: int=14
# הדגשת הקוד
highlighted_html=self.highlight_code(code, programming_language, 'html')
# יצירת HTML מלא
full_html=f"""
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
body {{
font-family: 'Courier New', monospace;
font-size: {font_size}px;
margin: 20px;
background-color: #f8f8f8;
line-height: 1.4;
}}
.highlight {{
background-color: white;
border: 1px solid #ddd;
border-radius: 5px;
padding: 15px;
overflow: auto;
}}
</style>
</head>
<body>
{highlighted_html}
</body>
</html>
"""
# המרה לתמונה (זה ידרוש התקנת wkhtmltopdf או כלי דומה)
# כרגע נחזיר placeholder
# יצירת תמונה פשוטה עם הקוד
ifImageisNoneorImageDrawisNone:
returnNone
img=Image.new('RGB', (width, max(400, len(code.split('\n')) *20)), 'white')
draw=ImageDraw.Draw(img)
try:
ifImageFontisnotNone:
font=ImageFont.truetype("DejaVuSansMono.ttf", font_size)
else:
font=None
exceptException:
font=ImageFont.load_default() ifImageFontisnotNoneelseNone
# כתיבת הקוד
y_position=10
forlineincode.split('\n'):
draw.text((10, y_position), line, fill='black', font=font)
y_position+=font_size+2
# המרה לבייטים
img_byte_arr_io=io.BytesIO()
img.save(img_byte_arr_io, format='PNG')
img_byte_arr: bytes=img_byte_arr_io.getvalue()
logger.info(f"נוצרה תמונת קוד בגודל {width}px")
returnimg_byte_arr
exceptExceptionase:
logger.error(f"שגיאה ביצירת תמונת קוד: {e}")
returnNone
defget_code_stats(self, code: str) ->Dict[str, Any]:
"""חישוב סטטיסטיקות קוד"""
lines=code.split('\n')
stats= {
'total_lines': len(lines),
'non_empty_lines': len([lineforlineinlinesifline.strip()]),
'comment_lines': 0,
'code_lines': 0,
'blank_lines': 0,
'characters': len(code),
'characters_no_spaces': len(code.replace(' ', '').replace('\t', '').replace('\n', '')),
'words': len(code.split()),
'functions': 0,
'classes': 0,
'complexity_score': 0
}
# ספירת סוגי שורות
forlineinlines:
stripped=line.strip()
ifnotstripped:
stats['blank_lines'] +=1
elifstripped.startswith('#') orstripped.startswith('//') orstripped.startswith('/*'):
stats['comment_lines'] +=1
else:
stats['code_lines'] +=1
# זיהוי פונקציות ומחלקות
stats['functions'] =len(re.findall(r'\bdef\s+\w+\s*\(|\bfunction\s+\w+\s*\(', code, re.IGNORECASE))
stats['classes'] =len(re.findall(r'\bclass\s+\w+\s*[:\{]', code, re.IGNORECASE))
# חישוב מורכבות בסיסית
complexity_indicators= [
'if ', 'elif ', 'else:', 'for ', 'while ', 'try:', 'except:', 'catch',
'switch', 'case:', 'break', 'continue', 'return', '&&', '||', '?:'
]
forindicatorincomplexity_indicators:
stats['complexity_score'] +=code.lower().count(indicator.lower())
# ניקוד קריאות (באמצעות textstat)
try:
iftextstatisnotNone:
stats['readability_score'] =textstat.flesch_reading_ease(code)
else:
stats['readability_score'] =0
exceptException:
stats['readability_score'] =0
logger.info(f"חושבו סטטיסטיקות לקוד: {stats['total_lines']} שורות, {stats['characters']} תווים")
returnstats
defanalyze_code(self, code: str, programming_language: str) ->Dict[str, Any]:
"""ניתוח קוד מהיר אך משמעותי לכל שפה
מחזיר מדדים כמו ציון איכות, מורכבות, בעיות נפוצות, שורות ארוכות ועוד.
"""
try:
language= (programming_languageor'text')
stats=self.get_code_stats(code)
# בסיס לציון איכות: מתחיל ב-100 ויורד לפי כשלים/מורכבות
quality_score=100
# עונשים על מורכבות גבוהה
complexity=int(stats.get('complexity_score', 0) or0)
ifcomplexity>80:
quality_score-=30
elifcomplexity>40:
quality_score-=20
elifcomplexity>20:
quality_score-=10
# שורות ארוכות
long_line_limit=120
lines=code.split('\n')
long_lines= [i+1fori, lninenumerate(lines) iflen(ln) >long_line_limit]
quality_score-=min(len(long_lines), 20) # עד 20 נק'
# הערות TODO/FIXME
todo_count=sum(1forlninlinesif ('TODO'inlnor'FIXME'inln))
quality_score-=min(todo_count*2, 10)
# יחס הערות נמוך מאוד (אם כמעט ואין הערות)
comment_lines=int(stats.get('comment_lines', 0))
total_lines=max(1, int(stats.get('total_lines', 1)))
iftotal_lines>=50andcomment_lines/total_lines<0.02:
quality_score-=5
# בדיקות תוכן בסיסיות לפי שפה
code_smells: List[str] = []
low=code.lower()
iflanguage.lower() =='python':
if'eval('inlow:
code_smells.append('eval שימוש מסוכן')
quality_score-=10
if'exec('inlow:
code_smells.append('exec שימוש מסוכן')
quality_score-=10
if'subprocess.Popen'incodeor'os.system('inlow:
code_smells.append('הרצת פקודות מערכת')
quality_score-=5
# בדיקת תחביר מהירה
syntax=self.validate_syntax(code, 'python')
ifnotsyntax.get('is_valid', True):
code_smells.append('שגיאות תחביר')
quality_score-=15
eliflanguage.lower() in ('javascript', 'typescript'):
if'eval('inlow:
code_smells.append('eval שימוש מסוכן')
quality_score-=10
if'document.write('inlow:
code_smells.append('document.write עלול להיות לא בטוח')
quality_score-=5
eliflanguage.lower() =='sql':
if'select *'inlow:
code_smells.append('SELECT * — מומלץ לציין עמודות')
quality_score-=3
eliflanguage.lower() in ('bash', 'sh'):
if'curl'inlowand'| sh'inlow:
code_smells.append('צינור curl ל-shell עלול להיות מסוכן')
quality_score-=10
# ניקוד סופי בגבולות [0, 100]
quality_score=max(0, min(100, quality_score))
return {
'quality_score': quality_score,
'complexity': complexity,
'long_lines': long_lines,
'readability': stats.get('readability_score', 0),
'summary': {
'total_lines': stats.get('total_lines', 0),
'functions': stats.get('functions', 0),
'classes': stats.get('classes', 0),
},
'code_smells': code_smells,
}
exceptExceptionase:
logger.error(f"שגיאה בניתוח קוד: {e}")
return {'error': str(e)}
defextract_functions(self, code: str, programming_language: str) ->List[Dict[str, Any]]:
"""חילוץ רשימת פונקציות מהקוד"""
functions: List[Dict[str, Any]] = []
patterns= {
'python': r'def\s+(\w+)\s*\([^)]*\)\s*:',
'javascript': r'function\s+(\w+)\s*\([^)]*\)\s*{',
'java': r'(?:public|private|protected)?\s*(?:static)?\s*\w+\s+(\w+)\s*\([^)]*\)\s*{',
'cpp': r'\w+\s+(\w+)\s*\([^)]*\)\s*{',
'c': r'\w+\s+(\w+)\s*\([^)]*\)\s*{',
'php': r'function\s+(\w+)\s*\([^)]*\)\s*{'
}
ifprogramming_languageinpatterns:
matches=re.finditer(patterns[programming_language], code, re.MULTILINE)
formatchinmatches:
func_name=match.group(1)
start_pos=match.start()
# מצא את השורה
lines_before=code[:start_pos].split('\n')
line_number=len(lines_before)
functions.append({
'name': func_name,
'line': line_number,
'signature': match.group(0)
})
logger.info(f"נמצאו {len(functions)} פונקציות בקוד")
returnfunctions
defvalidate_syntax(self, code: str, programming_language: str) ->Dict[str, Any]:
"""בדיקת תחביר של הקוד"""
fromtypingimportAny, Dict, List, TypedDict
class_ErrorDict(TypedDict, total=False):
line: int
message: str
type: str
class_ResultDict(TypedDict):
is_valid: bool
errors: List[_ErrorDict]
warnings: List[_ErrorDict]
suggestions: List[Dict[str, Any]]
result: _ResultDict= {
'is_valid': True,
'errors': [],
'warnings': [],
'suggestions': []
}
# בדיקות בסיסיות לפי שפה
ifprogramming_language=='python':
try:
compile(code, '<string>', 'exec')
exceptSyntaxErrorase:
result['is_valid'] =False
result['errors'].append({ # type: ignore[arg-type]
'line': e.lineno,
'message': str(e),
'type': 'SyntaxError'
})
elifprogramming_language=='json':
try:
importjson
json.loads(code)
exceptjson.JSONDecodeErrorase:
result['is_valid'] =False
result['errors'].append({ # type: ignore[arg-type]
'line': e.lineno,
'message': str(e),
'type': 'JSONDecodeError'
})
# בדיקות כלליות
lines=code.split('\n')
# בדיקת סוגריים מאוזנים
brackets_balance= {'(': 0, '[': 0, '{': 0}
fori, lineinenumerate(lines, 1):
forcharinline:
ifcharin'([{':
brackets_balance[char] +=1
elifcharin')]}':
opening_map= {')': '(', ']': '[', '}': '{'}
opening_bracket=opening_map.get(char)
ifopening_bracketandbrackets_balance[opening_bracket] >0:
brackets_balance[opening_bracket] -=1
else:
result['warnings'].append({ # type: ignore[arg-type]
'line': i,
'message': f'סוגריים לא מאוזנים: {char}',
'type': 'UnbalancedBrackets'
})
# בדיקה אם נותרו סוגריים פתוחים
forbracket, countinbrackets_balance.items():
ifcount>0:
result['warnings'].append({ # type: ignore[arg-type]
'line': len(lines),
'message': f'סוגריים לא סגורים: {bracket}',
'type': 'UnclosedBrackets'
})
# הצעות לשיפור
ifprogramming_language=='python':
# בדיקת import לא בשימוש
imports=re.findall(r'import\s+(\w+)', code)
forimpinimports:
ifcode.count(imp) ==1: # מופיע רק ב-import
result['suggestions'].append({
'message': f'ייבוא לא בשימוש: {imp}',
'type': 'UnusedImport'
})
logger.info(f"נבדק תחביר עבור {programming_language}: {'תקין'ifresult['is_valid'] else'לא תקין'}")
fromtypingimportcast, Dict, Any
returncast(Dict[str, Any], result)
defminify_code(self, code: str, programming_language: str) ->str:
"""דחיסת קוד (הסרת רווחים מיותרים והערות)"""
ifprogramming_language=='javascript':
# הסרת הערות חד-שורתיות
code=re.sub(r'//.*$', '', code, flags=re.MULTILINE)
# הסרת הערות רב-שורתיות
code=re.sub(r'/\*.*?\*/', '', code, flags=re.DOTALL)
# הסרת רווחים מיותרים
code=re.sub(r'\s+', ' ', code)
elifprogramming_language=='python':
lines=code.split('\n')
minified_lines= []