-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
9777 lines (8081 loc) · 417 KB
/
utils.py
File metadata and controls
9777 lines (8081 loc) · 417 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 json
import requests
from bs4 import BeautifulSoup
# PDF işlemleri için güvenli import
try:
from fpdf import FPDF
FPDF_AVAILABLE = True
except ImportError:
FPDF_AVAILABLE = False
FPDF = None
import tweepy
from datetime import datetime, timedelta
import hashlib
from dotenv import load_dotenv
from PIL import Image
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import time
import re
from difflib import SequenceMatcher
from email.utils import parsedate_to_datetime
# RSS parsing için güvenli import
try:
import feedparser
FEEDPARSER_AVAILABLE = True
except ImportError:
FEEDPARSER_AVAILABLE = False
feedparser = None
# emoji kütüphanesi yerine regex kullanacağız
# .env dosyasını yükle
load_dotenv()
# Web scraping için alternatif kütüphaneler (opsiyonel)
try:
import requests_html # type: ignore
REQUESTS_HTML_AVAILABLE = True
except ImportError:
REQUESTS_HTML_AVAILABLE = False
requests_html = None # type: ignore
try:
from selenium import webdriver # type: ignore
from selenium.webdriver.chrome.options import Options # type: ignore
from selenium.webdriver.common.by import By # type: ignore
from selenium.webdriver.support.ui import WebDriverWait # type: ignore
from selenium.webdriver.support import expected_conditions as EC # type: ignore
SELENIUM_AVAILABLE = True
except ImportError:
SELENIUM_AVAILABLE = False
webdriver = None # type: ignore
Options = None # type: ignore
By = None # type: ignore
WebDriverWait = None # type: ignore
EC = None # type: ignore
# .env dosyasını yükle
load_dotenv()
# Firecrawl MCP fonksiyonları için placeholder
def mcp_firecrawl_scrape(params):
"""Firecrawl MCP scrape fonksiyonu - Gelişmiş alternatif sistemli"""
try:
safe_print(f"[MCP] Firecrawl scrape çağrısı: {params.get('url', 'unknown')}")
url = params.get('url', '')
if not url:
return {"success": False, "error": "URL gerekli"}
# JavaScript gerekli mi kontrol et
use_js = any(domain in url.lower() for domain in [
'techcrunch.com', 'theverge.com', 'wired.com',
'arstechnica.com', 'venturebeat.com'
])
# Önce gelişmiş scraper dene
try:
safe_print(f"[MCP] Gelişmiş scraper deneniyor (JS: {use_js})...")
result = advanced_web_scraper(url, wait_time=3, use_js=use_js)
if result.get("success") and result.get("content"):
content = result.get("content", "")
safe_print(f"[MCP] Gelişmiş scraper başarılı: {len(content)} karakter ({result.get('method', 'unknown')})")
# HTML içeriğinden linkleri çıkar
links = []
html_content = result.get("html", "")
if html_content:
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_content, 'html.parser')
# Tüm linkleri bul
for link_elem in soup.find_all('a', href=True):
href = link_elem.get('href', '')
text = link_elem.get_text(strip=True)
if href and text and len(text) > 5:
# Relative URL'leri absolute yap
if href.startswith('/'):
from urllib.parse import urljoin
href = urljoin(url, href)
elif not href.startswith('http'):
continue
links.append({"text": text, "url": href})
return {
"success": True,
"content": content,
"markdown": content,
"links": links,
"source": f"advanced_scraper_{result.get('method', 'unknown')}",
"method": result.get('method', 'unknown')
}
else:
safe_print(f"[MCP] Gelişmiş scraper başarısız: {result.get('error', 'Bilinmeyen hata')}")
except Exception as advanced_error:
safe_print(f"[MCP] Gelişmiş scraper hatası: {advanced_error}")
# Fallback: Basit HTTP request
try:
safe_print(f"[MCP] Basit fallback deneniyor...")
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.9',
'Accept-Encoding': 'gzip, deflate',
'Connection': 'keep-alive'
}
session = requests.Session()
session.headers.update(headers)
response = session.get(url, timeout=30, allow_redirects=True)
response.raise_for_status()
soup = BeautifulSoup(response.text, 'html.parser')
content = extract_main_content(soup)
if content and len(content) > 100:
safe_print(f"[MCP] Basit fallback başarılı: {len(content)} karakter")
return {
"success": True,
"content": content,
"markdown": content,
"source": "simple_fallback"
}
else:
safe_print(f"[MCP] Basit fallback yetersiz içerik: {len(content) if content else 0} karakter")
except Exception as fallback_error:
safe_print(f"[MCP] Basit fallback hatası: {fallback_error}")
# Son çare: Sadece başlık çek
try:
safe_print(f"[MCP] Son çare: Sadece başlık çekiliyor...")
response = requests.get(url, timeout=15)
soup = BeautifulSoup(response.text, 'html.parser')
title = ""
title_selectors = ['title', 'h1', 'h2', '.title', '.headline']
for selector in title_selectors:
elem = soup.select_one(selector)
if elem:
title = elem.get_text(strip=True)
if len(title) > 10:
break
if title:
safe_print(f"[MCP] Son çare başarılı: Başlık çekildi")
return {
"success": True,
"content": title,
"markdown": title,
"source": "title_only"
}
except Exception as title_error:
safe_print(f"[MCP] Son çare hatası: {title_error}")
return {"success": False, "error": "Tüm yöntemler başarısız"}
except Exception as e:
safe_print(f"[MCP] Genel hata: {e}")
return {"success": False, "error": str(e)}
HISTORY_FILE = "posted_articles.json"
HASHTAG_FILE = "hashtags.json"
ACCOUNT_FILE = "accounts.json"
SUMMARY_FILE = "summaries.json"
MCP_CONFIG_FILE = "mcp_config.json"
def fetch_latest_ai_articles_with_firecrawl():
"""Firecrawl MCP ile gelişmiş haber çekme - Sadece son 4 makale"""
try:
# Önce mevcut yayınlanan makaleleri yükle
posted_articles = load_json(HISTORY_FILE)
posted_urls = [article.get('url', '') for article in posted_articles]
posted_hashes = [article.get('hash', '') for article in posted_articles]
safe_print("🔍 TechCrunch AI kategorisinden Firecrawl MCP ile makale çekiliyor...")
# Firecrawl MCP ile ana sayfa çek
try:
# Firecrawl MCP scrape fonksiyonunu kullan
scrape_result = mcp_firecrawl_scrape({
"url": "https://techcrunch.com/category/artificial-intelligence/",
"formats": ["markdown", "links"],
"onlyMainContent": True,
"waitFor": 2000
})
if not scrape_result.get("success", False):
safe_print(f"⚠️ Firecrawl MCP hatası, fallback yönteme geçiliyor...")
return fetch_latest_ai_articles_fallback()
# Hem markdown hem de links formatından URL çıkar
markdown_content = scrape_result.get("markdown", "")
mcp_links = scrape_result.get("links", [])
safe_print(f"📄 MCP'den {len(mcp_links)} link alındı, markdown: {len(markdown_content)} karakter")
import re
current_year = datetime.now().year
article_urls = []
# 1. MCP'den gelen linklerden makale URL'lerini çıkar
if mcp_links and isinstance(mcp_links, list):
for link_item in mcp_links:
if isinstance(link_item, dict):
url = link_item.get("url", "") or link_item.get("href", "")
elif isinstance(link_item, str):
url = link_item
else:
continue
if not url or 'techcrunch.com' not in url:
continue
# Yıl kontrolü
year_check = f'/{current_year}/' in url or f'/{current_year-1}/' in url
# Makale URL'si kontrolü (tarih formatı içermeli)
date_pattern = r'/\d{4}/\d{2}/\d{2}/'
is_article = re.search(date_pattern, url)
if (year_check and is_article and
url not in posted_urls and
url not in article_urls and
len(article_urls) < 10): # Daha fazla URL topla
article_urls.append(url)
print(f" 📰 MCP Link: {url}")
# 2. Markdown içeriğinden de URL çıkar (fallback)
if len(article_urls) < 4:
# Markdown'dan TechCrunch URL'lerini bul
markdown_urls = re.findall(r'https://techcrunch\.com/[^\s\)\]]+', markdown_content)
for url in markdown_urls:
# URL'yi temizle
url = url.rstrip(')')
# Yıl kontrolü
year_check = f'/{current_year}/' in url or f'/{current_year-1}/' in url
# Makale URL'si kontrolü (tarih formatı içermeli)
date_pattern = r'/\d{4}/\d{2}/\d{2}/'
is_article = re.search(date_pattern, url)
if (year_check and is_article and
url not in posted_urls and
url not in article_urls and
len(article_urls) < 10):
article_urls.append(url)
safe_print(f" 📄 Markdown Link: {url}")
# En yeni makaleleri al (sadece ilk 4)
article_urls = article_urls[:4]
safe_print(f"🔗 {len(article_urls)} makale URL'si bulundu")
except Exception as firecrawl_error:
safe_print(f"⚠️ Firecrawl MCP hatası: {firecrawl_error}")
safe_print("🔄 Fallback yönteme geçiliyor...")
return fetch_latest_ai_articles_fallback()
articles_data = []
for url in article_urls:
try:
# Her makaleyi Firecrawl MCP ile çek
article_content = fetch_article_content_with_firecrawl(url)
if article_content and len(article_content.get("content", "")) > 100:
title = article_content.get("title", "")
content = article_content.get("content", "")
# Makale hash'i oluştur
article_hash = hashlib.md5(title.encode()).hexdigest()
# Tekrar kontrolü
if article_hash not in posted_hashes:
articles_data.append({
"title": title,
"url": url,
"content": content,
"hash": article_hash,
"fetch_date": datetime.now().isoformat(),
"is_new": True,
"already_posted": False,
"source": "firecrawl_mcp"
})
print(f"🆕 Firecrawl ile yeni makale: {title[:50]}...")
else:
safe_print(f"✅ Makale zaten paylaşılmış: {title[:50]}...")
else:
safe_print(f"⚠️ İçerik yetersiz: {url}")
except Exception as article_error:
safe_print(f"❌ Makale çekme hatası ({url}): {article_error}")
continue
print(f"📊 Firecrawl MCP ile {len(articles_data)} yeni makale bulundu")
# Duplikat filtreleme uygula
if articles_data:
articles_data = filter_duplicate_articles(articles_data)
# Ana ayarlardan maksimum makale sayısını al
main_settings = load_automation_settings()
max_articles = main_settings.get('max_articles_per_run', 5)
print(f"🔢 Kullanıcı ayarına göre {max_articles} makale döndürülüyor")
return articles_data[:max_articles]
except Exception as e:
print(f"Firecrawl MCP haber çekme hatası: {e}")
safe_print("🔄 Fallback yönteme geçiliyor...")
return fetch_latest_ai_articles_fallback()
def fetch_latest_ai_articles():
"""Ana haber çekme fonksiyonu - Akıllı sistem ile"""
try:
# Yeni akıllı haber çekme sistemini kullan
return fetch_latest_ai_articles_smart()
except Exception as e:
safe_print(f"[HATA] Ana haber çekme hatası: {e}")
safe_print("[DENEME] Son çare fallback deneniyor...")
try:
return fetch_latest_ai_articles_fallback()
except Exception as fallback_error:
safe_print(f"[HATA] Fallback da başarısız: {fallback_error}")
return []
def fetch_latest_ai_articles_fallback():
"""Fallback haber çekme yöntemi - BeautifulSoup ile - Son 24 saat filtreli"""
try:
# 24 saat tarih filtresini ayarla
now = datetime.now()
twenty_four_hours_ago = now - timedelta(hours=24)
# Önce mevcut yayınlanan makaleleri yükle
posted_articles = load_json(HISTORY_FILE)
posted_urls = [article.get('url', '') for article in posted_articles]
posted_hashes = [article.get('hash', '') for article in posted_articles]
headers = {'User-Agent': 'Mozilla/5.0'}
html = requests.get("https://techcrunch.com/category/artificial-intelligence/", headers=headers).text
soup = BeautifulSoup(html, "html.parser")
article_links = soup.select("a.loop-card__title-link")[:4] # Sadece son 4 makale
safe_print(f"[FALLBACK] TechCrunch AI kategorisinden son {len(article_links)} makale kontrol ediliyor...")
articles_data = []
for link_tag in article_links:
title = link_tag.text.strip()
url = link_tag['href']
# URL'den tarih çıkarmaya çalış (TechCrunch format: /2024/08/12/)
article_date = None
import re
date_pattern = r'/(\d{4})/(\d{2})/(\d{2})/'
url_date_match = re.search(date_pattern, url)
if url_date_match:
try:
year, month, day = map(int, url_date_match.groups())
article_date = datetime(year, month, day)
# 24 saatten eski makaleleri filtrele
if article_date < twenty_four_hours_ago:
safe_print(f"⏰ Fallback makale 24 saatten eski: {article_date.strftime('%Y-%m-%d')} - {title[:50]}...")
continue
except:
pass
# Makale hash'i oluştur (başlık bazlı)
article_hash = hashlib.md5(title.encode()).hexdigest()
# Tekrar kontrolü - URL ve hash bazlı
is_already_posted = url in posted_urls or article_hash in posted_hashes
if is_already_posted:
safe_print(f"[ATLA] Makale zaten paylaşılmış, atlanıyor: {title[:50]}...")
continue
# Makale içeriğini gelişmiş şekilde çek
content = fetch_article_content_advanced(url, headers)
if content and len(content) > 100: # Minimum içerik kontrolü
articles_data.append({
"title": title,
"url": url,
"content": content,
"hash": article_hash,
"fetch_date": datetime.now().isoformat(),
"is_new": True, # Yeni makale işareti
"already_posted": False,
"source": "fallback"
})
safe_print(f"[YENI] Fallback ile yeni makale bulundu: {title[:50]}...")
else:
safe_print(f"[ATLA] İçerik yetersiz, atlanıyor: {title[:50]}...")
safe_print(f"[FALLBACK] Toplam {len(articles_data)} yeni makale bulundu")
# Duplikat filtreleme uygula
if articles_data:
articles_data = filter_duplicate_articles(articles_data)
# Ana ayarlardan maksimum makale sayısını al
main_settings = load_automation_settings()
max_articles = main_settings.get('max_articles_per_run', 5)
safe_print(f"[FALLBACK] Kullanıcı ayarına göre {max_articles} makale döndürülüyor")
return articles_data[:max_articles]
except Exception as e:
safe_print(f"[HATA] Fallback haber çekme hatası: {e}")
return []
def fetch_article_content_with_firecrawl(url):
"""Firecrawl MCP ile makale içeriği çekme"""
try:
safe_print(f"🔍 Firecrawl MCP ile makale çekiliyor: {url[:50]}...")
# Firecrawl MCP scrape fonksiyonunu kullan
scrape_result = mcp_firecrawl_scrape({
"url": url,
"formats": ["markdown"],
"onlyMainContent": True,
"waitFor": 3000,
"removeBase64Images": True
})
if not scrape_result.get("success", False):
safe_print(f"⚠️ Firecrawl MCP başarısız, fallback deneniyor...")
return fetch_article_content_advanced_fallback(url)
# Markdown içeriğini al
markdown_content = scrape_result.get("markdown", "")
if not markdown_content or len(markdown_content) < 100:
safe_print(f"⚠️ Firecrawl'dan yetersiz içerik, fallback deneniyor...")
return fetch_article_content_advanced_fallback(url)
# Başlığı çıkar (genellikle ilk # ile başlar)
lines = markdown_content.split('\n')
title = ""
content_lines = []
for line in lines:
line = line.strip()
if line.startswith('# ') and not title:
title = line[2:].strip()
elif line and not line.startswith('#') and len(line) > 20:
content_lines.append(line)
# İçeriği birleştir ve temizle
content = '\n'.join(content_lines)
# Gereksiz karakterleri temizle
content = content.replace('*', '').replace('**', '').replace('_', '')
content = ' '.join(content.split()) # Çoklu boşlukları tek boşluğa çevir
# İçeriği sınırla
content = content[:2500]
safe_print(f"✅ Firecrawl ile içerik çekildi: {len(content)} karakter")
return {
"title": title or "Başlık bulunamadı",
"content": content,
"source": "firecrawl_mcp"
}
except Exception as e:
safe_print(f"❌ Firecrawl MCP hatası ({url}): {e}")
safe_print("🔄 Fallback yönteme geçiliyor...")
return fetch_article_content_advanced_fallback(url)
def fetch_article_content_advanced_fallback(url):
"""Fallback makale içeriği çekme - BeautifulSoup ile"""
try:
headers = {'User-Agent': 'Mozilla/5.0'}
article_html = requests.get(url, headers=headers, timeout=10).text
article_soup = BeautifulSoup(article_html, "html.parser")
# Başlığı bul
title = ""
title_selectors = ["h1", "h1.entry-title", "h1.post-title", ".article-title h1"]
for selector in title_selectors:
title_elem = article_soup.select_one(selector)
if title_elem:
title = title_elem.text.strip()
break
# Çoklu selector deneme - daha kapsamlı içerik çekme
content_selectors = [
"div.article-content p",
"div.entry-content p",
"div.post-content p",
"article p",
"div.content p",
".article-body p"
]
content = ""
for selector in content_selectors:
paragraphs = article_soup.select(selector)
if paragraphs:
content = "\n".join([p.text.strip() for p in paragraphs if p.text.strip()])
if len(content) > 200: # Yeterli içerik bulundu
break
# Eğer hala içerik bulunamadıysa, tüm p etiketlerini dene
if not content:
all_paragraphs = article_soup.find_all('p')
content = "\n".join([p.text.strip() for p in all_paragraphs if len(p.text.strip()) > 50])
content = content[:2000] # İçeriği sınırla
return {
"title": title or "Başlık bulunamadı",
"content": content,
"source": "fallback"
}
except Exception as e:
print(f"Fallback makale içeriği çekme hatası ({url}): {e}")
return None
def fetch_article_content_advanced(url, headers):
"""Geriye dönük uyumluluk için eski fonksiyon"""
result = fetch_article_content_advanced_fallback(url)
return result.get("content", "") if result else ""
def load_json(path, default=None, limit=None):
"""JSON dosyasını yükle - limit parametresi ile performans optimizasyonu"""
if os.path.exists(path):
try:
with open(path, 'r', encoding='utf-8') as f:
data = json.load(f)
# Eğer limit belirtildiyse ve data bir liste ise, son N öğeyi al
if limit and isinstance(data, list) and len(data) > limit:
return data[-limit:]
return data
except json.JSONDecodeError as e:
print(f"JSON parse hatası ({path}): {e}")
return default if default is not None else []
except Exception as e:
print(f"Dosya okuma hatası ({path}): {e}")
return default if default is not None else []
return default if default is not None else []
def save_json(path, data):
"""JSON dosyasını kaydet - atomic write ile"""
import tempfile
import shutil
try:
# Geçici dosyaya yaz
temp_path = f"{path}.tmp"
with open(temp_path, "w", encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=2)
# Atomic move
shutil.move(temp_path, path)
except Exception as e:
# Geçici dosyayı temizle
if os.path.exists(f"{path}.tmp"):
try:
os.remove(f"{path}.tmp")
except:
pass
raise e
def summarize_article(article_content, api_key):
"""LLM ile gelişmiş makale özetleme"""
prompt = f"""Aşağıdaki AI/teknoloji haberini Türkçe olarak özetle. Özet tweet formatında, ilgi çekici ve bilgilendirici olsun:
Haber İçeriği:
{article_content[:1500]}
Lütfen:
- Maksimum 200 karakter
- Ana konuyu vurgula
- Teknik detayları basitleştir
- İlgi çekici bir dil kullan
Özet:"""
return gemini_call(prompt, api_key, max_tokens=100)
def score_article(article_content, api_key):
prompt = f"""Bu AI/teknoloji haberinin önemini 1-10 arasında değerlendir (sadece sayı):
{article_content[:800]}
Değerlendirme kriterleri:
- Yenilik derecesi
- Sektörel etki
- Geliştiriciler için önem
- Genel ilgi
Puan:"""
result = gemini_call(prompt, api_key, max_tokens=5)
try:
return int(result.strip().split()[0])
except:
return 5
def categorize_article(article_content, api_key):
prompt = f"""Bu haberin hedef kitlesini belirle:
{article_content[:500]}
Seçenekler: Developer, Investor, General
Cevap:"""
return gemini_call(prompt, api_key, max_tokens=10).strip()
def openrouter_call(prompt, api_key, max_tokens=100, model="moonshotai/kimi-k2:free"):
"""OpenRouter API çağrısı - Ücretsiz model ile yedek sistem"""
if not api_key:
safe_log("OpenRouter API anahtarı bulunamadı", "WARNING")
return None
try:
import requests
safe_log(f"OpenRouter API çağrısı yapılıyor... Model: {model}", "DEBUG")
safe_log(f"API Key format check: {api_key[:8]}... (length: {len(api_key)})", "DEBUG")
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
"HTTP-Referer": "https://ai-tweet-bot.pythonanywhere.com",
"X-Title": "AI Tweet Bot"
}
data = {
"model": model,
"messages": [
{
"role": "user",
"content": prompt
}
],
"max_tokens": max_tokens,
"temperature": 0.7,
"top_p": 0.9,
"frequency_penalty": 0.1,
"presence_penalty": 0.1
}
response = requests.post(
"https://openrouter.ai/api/v1/chat/completions",
headers=headers,
json=data,
timeout=30
)
safe_log(f"OpenRouter API Response Status: {response.status_code}", "DEBUG")
if response.status_code == 200:
result = response.json()
if result.get("choices") and len(result["choices"]) > 0:
content = result["choices"][0]["message"]["content"].strip()
safe_log(f"OpenRouter API yanıtı alındı: {len(content)} karakter", "DEBUG")
return content
else:
safe_log("OpenRouter API yanıtında choices bulunamadı", "WARNING")
safe_log(f"Response content: {result}", "DEBUG")
return None
elif response.status_code == 401:
safe_log(f"OpenRouter API 401 Unauthorized - API anahtarı geçersiz", "ERROR")
safe_log(f"Response: {response.text}", "ERROR")
safe_log(f"Headers sent: Authorization=Bearer {api_key[:10]}...", "DEBUG")
return None
elif response.status_code == 429:
safe_log(f"OpenRouter API 429 Rate Limited", "ERROR")
safe_log(f"Response: {response.text}", "ERROR")
return None
else:
safe_log(f"OpenRouter API hatası: {response.status_code} - {response.text}", "ERROR")
return None
except Exception as e:
safe_log(f"OpenRouter API çağrı hatası: {str(e)}", "ERROR")
return None
def ai_call(prompt, api_key=None, max_tokens=100):
"""AI API çağrısı - Sadece OpenRouter kullanılır"""
# OpenRouter API anahtarını al
openrouter_key = api_key or os.environ.get('OPENROUTER_API_KEY')
if not openrouter_key:
safe_log("❌ OpenRouter API anahtarı bulunamadı", "ERROR")
return None # None döndür, hata mesajı değil
safe_log("[OpenRouter] API çağrısı yapılıyor...", "INFO")
try:
result = openrouter_call(prompt, openrouter_key, max_tokens)
if result and result != "API hatası" and len(result.strip()) > 10: # Minimum 10 karakter kontrolü
safe_log(f"✅ OpenRouter başarılı: {len(result)} karakter", "SUCCESS")
return result
else:
safe_log("⚠️ OpenRouter yanıtı yetersiz", "WARNING")
return None # None döndür, hata mesajı değil
except Exception as e:
safe_log(f"❌ OpenRouter API hatası: {str(e)}", "ERROR")
return None # None döndür, hata mesajı değil
# Geriye uyumluluk için gemini_call fonksiyonunu ai_call'a yönlendir
def gemini_call(prompt, api_key, max_tokens=100):
"""Geriye uyumluluk için - artık OpenRouter kullanır"""
return ai_call(prompt, api_key, max_tokens)
def try_openrouter_fallback(prompt, max_tokens=100):
"""OpenRouter yedek sistemini dene"""
try:
# OpenRouter API anahtarını kontrol et
openrouter_key = os.environ.get('OPENROUTER_API_KEY')
if not openrouter_key:
safe_log("[UYARI] OpenRouter API anahtarı bulunamadı, yedek sistem kullanılamıyor", "WARNING")
return None
safe_log("[FALLBACK] Gemini başarısız, OpenRouter yedek sistemi deneniyor...", "INFO")
# Güncel ücretsiz modeller listesi (2025 - kullanıcı tarafından belirtilen modeller öncelikli)
free_models = [
"moonshotai/kimi-k2:free", # Test edildi - Çalışıyor
"openrouter/auto", # Test edildi - Çalışıyor (otomatik model seçimi)
"mistralai/mistral-7b-instruct:free", # Test edildi - Çalışıyor
# Yedek modeller (gerektiğinde test edilecek)
"qwen/qwen3-coder:free", # Geçici rate limited
"google/gemma-3n-e2b-it:free" # Geçici rate limited
]
# Her modeli sırayla dene
for model in free_models:
try:
safe_log(f"[TEST] OpenRouter modeli deneniyor: {model}", "DEBUG")
result = openrouter_call(prompt, openrouter_key, max_tokens, model)
if result and len(result.strip()) > 5:
safe_log(f"[BASARILI] OpenRouter başarılı! Model: {model}", "SUCCESS")
return result
else:
safe_log(f"[UYARI] OpenRouter model yanıt vermedi: {model}", "WARNING")
continue
except Exception as model_error:
safe_log(f"[HATA] OpenRouter model hatası ({model}): {model_error}", "ERROR")
continue
# Hiçbir model çalışmazsa
safe_log("[HATA] Tüm OpenRouter modelleri başarısız", "ERROR")
return None
except Exception as e:
safe_log(f"[HATA] OpenRouter yedek sistem hatası: {e}", "ERROR")
return None
def generate_smart_hashtags(title, content):
"""Makale içeriğine göre akıllı hashtag oluşturma - İçeriğe özgü analiz"""
combined_text = f"{title.lower()} {content.lower()}"
hashtags = []
priority_hashtags = [] # Yüksek öncelikli hashtag'ler
# Makale başlığından anahtar kelimeleri çıkar
title_keywords = extract_article_keywords(title, content)
# Başlıktan çıkarılan anahtar kelimeleri hashtag'e çevir
for keyword in title_keywords[:3]: # En önemli 3 anahtar kelime
hashtag = create_hashtag_from_keyword(keyword)
if hashtag:
priority_hashtags.append(hashtag)
# Şirket özel hashtag'leri (yüksek öncelik)
company_hashtags = []
if "openai" in combined_text:
company_hashtags.extend(["#OpenAI", "#ChatGPT", "#GPT"])
if "google" in combined_text:
company_hashtags.extend(["#Google", "#GoogleAI", "#Gemini"])
if "microsoft" in combined_text:
company_hashtags.extend(["#Microsoft", "#Azure", "#Copilot"])
if "meta" in combined_text:
company_hashtags.extend(["#Meta", "#MetaAI", "#Llama"])
if "apple" in combined_text:
company_hashtags.extend(["#Apple", "#iOS", "#AppleAI"])
if "tesla" in combined_text:
company_hashtags.extend(["#Tesla", "#ElonMusk", "#Autopilot"])
if "nvidia" in combined_text:
company_hashtags.extend(["#NVIDIA", "#GPU", "#CUDA"])
if "anthropic" in combined_text:
company_hashtags.extend(["#Anthropic", "#Claude"])
if "amazon" in combined_text:
company_hashtags.extend(["#Amazon", "#AWS", "#Alexa"])
if "x.ai" in combined_text or "xai" in combined_text:
company_hashtags.extend(["#xAI", "#ElonMusk"])
# Teknoloji alanları (orta öncelik)
tech_hashtags = []
if any(keyword in combined_text for keyword in ["artificial intelligence", "ai", "machine learning", "ml", "neural", "deep learning", "llm", "large language model"]):
tech_hashtags.extend(["#ArtificialIntelligence", "#MachineLearning", "#DeepLearning", "#LLM"])
if any(keyword in combined_text for keyword in ["robotics", "robot", "automation", "autonomous", "self-driving"]):
tech_hashtags.extend(["#Robotics", "#Automation", "#AutonomousVehicles"])
if any(keyword in combined_text for keyword in ["quantum", "quantum computing", "quantum supremacy"]):
tech_hashtags.extend(["#QuantumComputing", "#QuantumSupremacy", "#QuantumTech"])
if any(keyword in combined_text for keyword in ["blockchain", "crypto", "bitcoin", "ethereum", "web3", "nft"]):
tech_hashtags.extend(["#Blockchain", "#Cryptocurrency", "#Web3", "#NFT"])
if any(keyword in combined_text for keyword in ["ar", "vr", "augmented reality", "virtual reality", "metaverse", "mixed reality"]):
tech_hashtags.extend(["#AR", "#VR", "#Metaverse", "#MixedReality"])
if any(keyword in combined_text for keyword in ["cybersecurity", "security", "privacy", "encryption", "data breach"]):
tech_hashtags.extend(["#Cybersecurity", "#DataPrivacy", "#InfoSec"])
if any(keyword in combined_text for keyword in ["cloud", "aws", "azure", "gcp", "serverless"]):
tech_hashtags.extend(["#CloudComputing", "#ServerlessComputing", "#CloudNative"])
if any(keyword in combined_text for keyword in ["iot", "internet of things", "smart home", "smart city"]):
tech_hashtags.extend(["#IoT", "#SmartHome", "#SmartCity"])
if any(keyword in combined_text for keyword in ["5g", "6g", "network", "connectivity", "telecommunications"]):
tech_hashtags.extend(["#5G", "#6G", "#Telecommunications"])
if any(keyword in combined_text for keyword in ["biotech", "biotechnology", "medical ai", "healthcare ai"]):
tech_hashtags.extend(["#BioTech", "#MedicalAI", "#HealthTech"])
# İş ve finansal hashtag'ler
business_hashtags = []
if any(keyword in combined_text for keyword in ["startup", "funding", "investment", "venture", "ipo", "acquisition"]):
business_hashtags.extend(["#Startup", "#Investment", "#VentureCapital", "#IPO"])
if any(keyword in combined_text for keyword in ["billion", "million", "revenue", "valuation", "profit"]):
business_hashtags.extend(["#Business", "#Revenue", "#TechBusiness"])
# Spesifik ürün/teknoloji hashtag'leri
product_hashtags = []
if any(keyword in combined_text for keyword in ["chatgpt", "gpt-4", "gpt-5"]):
product_hashtags.extend(["#ChatGPT", "#GPT4", "#GPT5"])
if any(keyword in combined_text for keyword in ["claude", "claude-3", "claude-4"]):
product_hashtags.extend(["#Claude", "#ClaudeAI"])
if any(keyword in combined_text for keyword in ["gemini", "bard", "palm"]):
product_hashtags.extend(["#Gemini", "#GoogleAI", "#PaLM"])
if any(keyword in combined_text for keyword in ["github copilot", "copilot", "code assistant"]):
product_hashtags.extend(["#GitHubCopilot", "#CodeAssistant"])
# Öncelik sırasına göre hashtag'leri birleştir
priority_hashtags.extend(company_hashtags[:2]) # En fazla 2 şirket hashtag'i
priority_hashtags.extend(product_hashtags[:1]) # En fazla 1 ürün hashtag'i
priority_hashtags.extend(tech_hashtags[:2]) # En fazla 2 teknoloji hashtag'i
priority_hashtags.extend(business_hashtags[:1]) # En fazla 1 iş hashtag'i
# Genel teknoloji hashtag'leri (düşük öncelik)
general_hashtags = ["#Innovation", "#Technology", "#TechNews", "#AI", "#FutureTech"]
# Tekrarları kaldır
unique_hashtags = list(dict.fromkeys(priority_hashtags))
# En fazla 5 hashtag seç
selected_hashtags = unique_hashtags[:5]
# Eğer 5'ten az varsa, genel hashtag'lerle tamamla
if len(selected_hashtags) < 5:
remaining_general = [h for h in general_hashtags if h not in selected_hashtags]
selected_hashtags.extend(remaining_general[:5-len(selected_hashtags)])
return selected_hashtags[:5]
def extract_article_keywords(title, content):
"""Makale başlığından anahtar kelimeleri çıkar"""
import re
# Başlık ve içerikteki önemli kelimeleri bul
text = f"{title} {content[:500]}"
# Teknoloji terimlerini önceliklendirme
tech_terms = [
'artificial intelligence', 'machine learning', 'deep learning', 'neural network',
'quantum computing', 'blockchain', 'cryptocurrency', 'robotics', 'automation',
'augmented reality', 'virtual reality', 'cloud computing', 'cybersecurity',
'internet of things', '5g', '6g', 'biotechnology', 'nanotechnology'
]
found_terms = []
for term in tech_terms:
if term.lower() in text.lower():
found_terms.append(term)
# Şirket isimleri
companies = [
'OpenAI', 'Google', 'Microsoft', 'Apple', 'Meta', 'Tesla', 'NVIDIA',
'Amazon', 'Anthropic', 'xAI', 'DeepMind', 'Hugging Face'
]
for company in companies:
if company.lower() in text.lower():
found_terms.append(company)
# Önemli sayısal değerler
numbers = re.findall(r'\b(\d+(?:\.\d+)?)\s*(billion|million|percent|%|x|times)\b', text.lower())
if numbers:
found_terms.append(f"{numbers[0][0]}{numbers[0][1]}")
return found_terms[:5]
def create_hashtag_from_keyword(keyword):
"""Anahtar kelimeden hashtag oluştur"""
if not keyword:
return None
# Özel durumlar
keyword_mappings = {
'artificial intelligence': '#ArtificialIntelligence',
'machine learning': '#MachineLearning',
'deep learning': '#DeepLearning',
'quantum computing': '#QuantumComputing',
'augmented reality': '#AugmentedReality',
'virtual reality': '#VirtualReality',
'cloud computing': '#CloudComputing',
'internet of things': '#IoT',
'neural network': '#NeuralNetworks',
'openai': '#OpenAI',
'chatgpt': '#ChatGPT',
'tesla': '#Tesla',
'nvidia': '#NVIDIA',
'google': '#Google',
'microsoft': '#Microsoft',
'apple': '#Apple',
'meta': '#Meta',
'anthropic': '#Anthropic'
}
keyword_lower = keyword.lower()
if keyword_lower in keyword_mappings:
return keyword_mappings[keyword_lower]
# Genel hashtag oluşturma kuralları
# Boşlukları kaldır ve her kelimenin ilk harfini büyüt
words = keyword.split()
if len(words) == 1:
return f"#{words[0].capitalize()}"
elif len(words) <= 3:
hashtag = ''.join([word.capitalize() for word in words])
return f"#{hashtag}"
return None
def generate_smart_emojis(title, content):
"""Makale içeriğine göre akıllı emoji seçimi"""
combined_text = f"{title.lower()} {content.lower()}"
emojis = []
# Konu bazlı emojiler
if any(keyword in combined_text for keyword in ["ai", "artificial intelligence", "robot", "machine learning"]):
emojis.extend(["🤖", "🧠", "⚡"])
if any(keyword in combined_text for keyword in ["funding", "investment", "billion", "million", "money"]):
emojis.extend(["💰", "💸", "📈"])
if any(keyword in combined_text for keyword in ["launch", "release", "unveil", "announce"]):
emojis.extend(["🚀", "🎉", "✨"])
if any(keyword in combined_text for keyword in ["research", "development", "breakthrough", "discovery"]):
emojis.extend(["🔬", "💡", "🧪"])
if any(keyword in combined_text for keyword in ["security", "privacy", "protection", "safe"]):
emojis.extend(["🔒", "🛡️", "🔐"])
if any(keyword in combined_text for keyword in ["acquisition", "merger", "partnership"]):
emojis.extend(["🤝", "🔗", "💼"])
if any(keyword in combined_text for keyword in ["search", "query", "find", "discover"]):
emojis.extend(["🔍", "🔎", "📊"])
if any(keyword in combined_text for keyword in ["mobile", "phone", "app", "smartphone"]):
emojis.extend(["📱", "📲", "💻"])
if any(keyword in combined_text for keyword in ["cloud", "server", "data", "storage"]):
emojis.extend(["☁️", "💾", "🗄️"])