benim ana kodum aşağıdaki gibidir Gerekli kütüphaneleri yükleyin !pip install pandas…
- User
benim ana kodum aşağıdaki gibidir
Gerekli kütüphaneleri yükleyin
!pip install pandas pillow requests !apt-get install -y ttf-mscorefonts-installer
import requests import xml.etree.ElementTree as ET import pandas as pd from PIL import Image, ImageDraw, ImageFont, UnidentifiedImageError from io import BytesIO import re import textwrap import zipfile import os from google.colab import files # Dosya yükleme için
Kullanıcıdan gerekli bilgileri alma
rss_url = input("RSS adresini girin: ") news_count = int(input("Çekmek istediğiniz haber sayısını girin: "))
Kullanıcıdan yazı fontunu yüklemesini isteyin
print("Yazı fontunu yükleyin (TTF formatında):") uploaded_font = files.upload() # Kullanıcının font dosyasını yüklemesini sağlar font_path = next(iter(uploaded_font)) # Yüklenen font dosyasının adını al
Kullanıcıdan logo yüklemesini isteyin
print("Logo dosyasını yükleyin (PNG formatında veya başka bir format):") uploaded_logo = files.upload() # Kullanıcının logo dosyasını yüklemesini sağlar logo_path = next(iter(uploaded_logo)) # Yüklenen logo dosyasının adını al
RSS'den veri çekme fonksiyonu
def fetch_rss_data(rss_url, num_items): headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36' } response = requests.get(rss_url, headers=headers) rss_content = response.text
# RSS XML'ini parse et root = ET.fromstring(rss_content) items = root.findall('.//item') news_data = [] for item in items[:num_items]: title = item.find('.//title').text if item.find('.//title') is not None else 'Başlık Yok' description = item.find('.//description').text if item.find('.//description') is not None else 'Açıklama Yok' # Görsel URL'sini alma image_url = None # 1. <image> etiketi image_tag = item.find('.//image') if image_tag is not None: image_url = image_tag.text # 2. <imageUrl> etiketi if not image_url: image_tag = item.find('.//imageUrl') if image_tag is not None: image_url = image_tag.text # 3. <media:content> etiketi if not image_url: media_content_tag = item.find('.//media:content', namespaces={'media': 'http://search.yahoo.com/mrss/'}) if media_content_tag is not None and 'url' in media_content_tag.attrib: image_url = media_content_tag.attrib['url'] # 4. <enclosure> etiketi if not image_url: enclosure_tag = item.find('.//enclosure') if enclosure_tag is not None and 'url' in enclosure_tag.attrib: image_url = enclosure_tag.attrib['url'] # Sonuç listesine ekle news_data.append((title, description, image_url)) return news_dataRSS verisini çek
data = fetch_rss_data(rss_url, news_count)
Pandas DataFrame oluştur
df = pd.DataFrame(data, columns=['Title', 'Description', 'Image URL'])
CSV dosyasına kaydet
csv_file_path = '/content/yalova.csv' df.to_csv(csv_file_path, index=False)
CSV dosyasının kaydedildiğini göster
print(f"{news_count} haber başarıyla çekildi ve CSV dosyasına kaydedildi: {csv_file_path}")
Font ve boyut ayarları
title_font_size = 35 description_font_size = 25 title_font = ImageFont.truetype(font_path, title_font_size) description_font = ImageFont.truetype(font_path, description_font_size)
Instagram gönderisi için 1080x1080 boyutunda bir kare oluşturur.
post_size = (1080, 1080)
Logo dosyasını yükle
logo_size = (120, 120) logo = Image.open(logo_path).resize(logo_size)
def wrap_text(text, width): lines = textwrap.wrap(text, width=width) return "\n".join(lines)
def create_post(title, description, img_url, output_folder): headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36', 'Referer': 'https://yalovagazetesi.com' } default_image_url = "/content/3d-success-text-perspective-with-words_93487-102.avif"
try: response = requests.get(img_url, headers=headers, timeout=10) response.raise_for_status() if "image" not in response.headers.get("Content-Type", ""): print(f"Bu URL bir resim içermiyor: {img_url}") response = requests.get(default_image_url, headers=headers, timeout=10) except Exception as e: print(f"Resim indirilemedi: {img_url} - Hata: {e}. Varsayılan görsel kullanılacak.") response = requests.get(default_image_url, headers=headers, timeout=10) try: img = Image.open(BytesIO(response.content)) except UnidentifiedImageError: print(f"Varsayılan görsel de yüklenemedi: {default_image_url}") return None img = img.resize(post_size) draw = ImageDraw.Draw(img) title = wrap_text(title, 50).upper() description = wrap_text(description, 80).upper() title_bbox = draw.textbbox((0, 0), title, font=title_font) description_bbox = draw.textbbox((0, 0), description, font=description_font) title_width, title_height = title_bbox[2] - title_bbox[0], title_bbox[3] - title_bbox[1] description_width, description_height = description_bbox[2] - description_bbox[0], description_bbox[3] - description_bbox[1] title_x = 30 description_x = 30 total_height = title_height + description_height title_y = (post_size[1] - total_height) / 2 + 280 description_y = title_y + title_height + 70 draw.rectangle([title_x - 20, title_y - 20, title_width + title_x + 20, title_y + title_height + 20], fill=(0, 107, 107)) draw.rectangle([description_x - 20, description_y - 20, description_width + description_x + 20, description_y + description_height + 20], fill=(255, 255, 255)) draw.text((title_x, title_y), title, font=title_font, fill=(255, 255, 255)) draw.text((description_x, description_y), description, font=description_font, fill=(0, 0, 0)) img.paste(logo, (post_size[0] - logo_size[0] - 30, 30), logo) safe_title = re.sub(r'[^\w\-_\. ]', '_', title[:10]) post_filename = os.path.join(output_folder, f"post_{safe_title}.jpg") img.save(post_filename) return post_filenameKullanılacak CSV dosyaları
csv_files = [ (csv_file_path, "posts_yalova.zip"), ]
Her bir CSV dosyası için işlem yapar
for csv_file, zip_filename in csv_files: output_folder = f"/content/posts_{os.path.splitext(os.path.basename(csv_file))[0]}" os.makedirs(output_folder, exist_ok=True)
df = pd.read_csv(csv_file) with zipfile.ZipFile(f"/content/{zip_filename}", 'w') as zipf: for index, row in df.iterrows(): title = row['Title'] description = row['Description'] img_url = row['Image URL'] try: post_filename = create_post(title, description, img_url, output_folder) if post_filename: zipf.write(post_filename, os.path.basename(post_filename)) os.remove(post_filename) except Exception as e: print(f"Hata oluştu: {e}") print(f"{zip_filename} dosyası oluşturuldu.")Tüm ZIP dosyalarını indirilebilir hale getir
for _, zip_filename in csv_files: files.download(f"/content/{zip_filename}")
ve son olarak duzenledıgım kod aşağıdaki gibi import requests import xml.etree.ElementTree as ET import pandas as pd from PIL import Image, ImageDraw, ImageFont, UnidentifiedImageError import zipfile import os from io import BytesIO import re import html import textwrap import streamlit as st
RSS'den veri çekme fonksiyonu
def fetch_rss_data(rss_url, num_items): headers = {'User-Agent': 'Mozilla/5.0'} response = requests.get(rss_url, headers=headers) rss_content = response.text
# RSS XML'ini parse et root = ET.fromstring(rss_content) items = root.findall('.//item') news_data = [] for item in items[:num_items]: title = item.find('.//title').text if item.find('.//title') is not None else 'Başlık Yok' description = item.find('.//description').text if item.find('.//description') is not None else 'Açıklama Yok' # CDATA etiketlerini temizleme description = re.sub(r'<!\[CDATA\[(.*?)\]\]>', r'\1', description) description = html.unescape(description) # Görsel URL'sini alma image_url = None image_tag = item.find('.//image') or item.find('.//imageUrl') or \ item.find('.//media:content', namespaces={'media': 'http://search.yahoo.com/mrss/'}) or \ item.find('.//enclosure') if image_tag is not None and 'url' in image_tag.attrib: image_url = image_tag.attrib['url'] if image_tag.tag == 'enclosure' and 'url' in image_tag.attrib else image_tag.text news_data.append((title, description, image_url)) return news_dataGörsel oluşturma fonksiyonu
def wrap_text(text, width): lines = textwrap.wrap(text, width=width) return "\n".join(lines)
def create_post(title, description, img_url, output_folder, title_font, description_font, title_bg_color, description_bg_color, title_text_color, description_text_color, logo, logo_position): headers = {'User-Agent': 'Mozilla/5.0'} default_image_url = "https://via.placeholder.com/1080" # Varsayılan bir görsel URL'si
try: response = requests.get(img_url, headers=headers, timeout=10) response.raise_for_status() if "image" not in response.headers.get("Content-Type", ""): response = requests.get(default_image_url, headers=headers, timeout=10) except Exception: response = requests.get(default_image_url, headers=headers, timeout=10) try: img = Image.open(BytesIO(response.content)) except UnidentifiedImageError: return None img = img.resize((1080, 1080)) draw = ImageDraw.Draw(img) wrapped_title = wrap_text(title, 50).upper() wrapped_description = wrap_text(description, 80).upper() title_bbox = draw.textbbox((0, 0), wrapped_title, font=title_font) description_bbox = draw.textbbox((0, 0), wrapped_description, font=description_font) title_width, title_height = title_bbox[2] - title_bbox[0], title_bbox[3] - title_bbox[1] description_width, description_height = description_bbox[2] - description_bbox[0], description_bbox[3] - description_bbox[1] # Başlık konumunu ayarlama title_x = 30 if title_alignment == "Sol" else 1080 - title_width - 30 description_x = 30 if description_alignment == "Sol" else 1080 - description_width - 30 total_height = title_height + description_height title_y = (1080 - total_height) / 2 + 280 description_y = title_y + title_height + 70 # Oval kutular oluşturma corner_radius = 20 # Oval köşe yarıçapı draw.rounded_rectangle([title_x - 20, title_y - 20, title_width + title_x + 20, title_y + title_height + 20], radius=corner_radius, fill=title_bg_color) draw.rounded_rectangle([description_x - 20, description_y - 20, description_width + description_x + 20, description_y + description_height + 20], radius=corner_radius, fill=description_bg_color) draw.text((title_x, title_y), wrapped_title, font=title_font, fill=title_text_color) draw.text((description_x, description_y), wrapped_description, font=description_font, fill=description_text_color) logo_resized = logo.resize((logo_size, logo_size)) if logo_position == "Sol Üst": logo_x, logo_y = 30, 30 else: # Sağ Üst logo_x, logo_y = 1080 - logo_size - 30, 30 img.paste(logo_resized, (logo_x, logo_y), logo_resized) safe_title = re.sub(r'[^\w\-_\. ]', '_', title[:10]) post_filename = os.path.join(os.path.dirname(output_folder), f"post_{safe_title}.jpg") os.makedirs(os.path.dirname(output_folder), exist_ok=True) img.save(post_filename) return post_filenameZIP dosyasını oluşturma ve indirme fonksiyonu
def create_zip_from_posts(csv_data, output_folder, logo_position): with zipfile.ZipFile(output_folder, 'w') as zipf: for index, row in csv_data.iterrows(): title = row['Title'] description = row['Description'] img_url = row['Image URL']
post_filename = create_post(title, description, img_url, output_folder, title_font, description_font, title_bg_color, description_bg_color, title_text_color, description_text_color, logo, logo_position) if post_filename: zipf.write(post_filename, os.path.basename(post_filename)) os.remove(post_filename)Streamlit UI ile işlemi başlatma
st.title("RSS Feed Görsel Oluşturucu") rss_url = st.text_input("RSS adresini girin:") news_count = st.number_input("Çekmek istediğiniz haber sayısını girin:", min_value=1, step=1)
Logo konumu ve dosya yükleme
logo_position = st.selectbox("Logonun konumunu seçin:", options=["Sol Üst", "Sağ Üst"]) uploaded_font = st.file_uploader("Yazı fontunu yükleyin (TTF formatında)", type=["ttf"]) uploaded_logo = st.file_uploader("Logo dosyasını yükleyin (PNG formatında)", type=["png", "jpg", "jpeg"])
Kutu ve metin renkleri
title_bg_color = st.color_picker("Başlık arka plan rengini seçin:", "#009999") description_bg_color = st.color_picker("Açıklama arka plan rengini seçin:", "#FFFFFF") title_text_color = st.color_picker("Başlık metni rengini seçin:", "#FFFFFF") description_text_color = st.color_picker("Açıklama metni rengini seçin:", "#000000")
Font boyutlarını ayarlama
title_font_size = st.number_input("Başlık font boyutunu ayarlayın:", min_value=10, max_value=100, value=35) description_font_size = st.number_input("Açıklama font boyutunu ayarlayın:", min_value=10, max_value=100, value=25)
Metin konumu ayarlama için seçim aracı
title_alignment = st.selectbox("Başlık konumunu seçin:", options=["Sol", "Sağ"]) description_alignment = st.selectbox("Açıklama konumunu seçin:", options=["Sol", "Sağ"])
Logo boyutunu sabit olarak belirleme
logo_size = 150 # Logo boyutu: 150x150
Yardım Dokümanları
st.sidebar.header("Yardım") st.sidebar.write(""" Uygulama Rehberi:
- RSS adresi girin ve kaç haber çekmek istediğinizi seçin.
- Logo ve font dosyalarınızı yükleyin.
- Başlık ve açıklama konumlarını ve renklerini ayarlayın.
- "Gönder" butonuna basarak gerekli işlemleri tamamlayın. """)
if st.button('Gönder'): if rss_url and uploaded_font and uploaded_logo: # ZIP dosyası için dizini belirleme zip_dir = os.path.join(os.path.expanduser("~"), "Desktop", "post") os.makedirs(zip_dir, exist_ok=True) # Dizin yoksa oluştur
# ZIP dosyasının tam yolunu belirleme output_zip_path = os.path.join(zip_dir, "posts.zip") # RSS verilerini al data = fetch_rss_data(rss_url, news_count) if data: df = pd.DataFrame(data, columns=['Title', 'Description', 'Image URL']) # Fontu yükleme title_font = None description_font = None if uploaded_font: try: font_bytes = uploaded_font.read() title_font = ImageFont.truetype(BytesIO(font_bytes), title_font_size) description_font = ImageFont.truetype(BytesIO(font_bytes), description_font_size) except Exception as e: st.error(f"Font yüklenirken bir hata oluştu: {e}") # Logo dosyasını yükleme logo = None if uploaded_logo: logo = Image.open(uploaded_logo) # ZIP dosyasının oluşturulması create_zip_from_posts(df, output_zip_path, logo_position) # ZIP dosyasını oku ve akışa yaz with open(output_zip_path, 'rb') as f: st.download_button("ZIP Dosyasını İndir", data=f, file_name="posts.zip", mime="application/zip") else: st.error("Hatalı RSS URL veya veri bulunamadı.") else: st.error("Lütfen tüm alanları doldurun: RSS URL, Font, Logo.")fakat bu son olarak duzenledıgım kodda aldıgım hata xml.etree.ElementTree.ParseError: This app has encountered an error. The original error message is redacted to prevent data leaks. Full error details have been recorded in the logs (if you're on Streamlit Cloud, click on 'Manage app' in the lower right of your app). Traceback: File "/mount/src/autopostcreator/autopostcreator.py", line 174, in data = fetch_rss_data(rss_url, news_count) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/mount/src/autopostcreator/autopostcreator.py", line 20, in fetch_rss_data root = ET.fromstring(rss_content) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/xml/etree/ElementTree.py", line 1335, in XML parser.feed(text) ve ornek rss adresı :https://www.cnnturk.com/feed/rss/all/news bu
- Assistant
Hatanız,
xml.etree.ElementTree.ParseErrorhatasıdır ve genellikle XML içeriği beklenildiği gibi yapılandırılmadığında ortaya çıkar. Bu durumda,rss_contentolarak aldığınız verinin geçerli bir XML formatında olmadığını gösteriyor. Bunun birkaç nedeni olabilir:-
URL Erişimi: Belirttiğiniz RSS URL'sinin düzgün bir şekilde erişilebilir olduğundan ve yanıtın düzgün bir formatta geldiğinden emin olun. Örneğin, tarayıcıda bu URL'yi açarak içeriği kontrol edin.
-
Yanıt Bilgisi: Bazen, bir istek (request) yapıldığında, sunucu bir hata durumu geri döndürebilir. Bunun yerine XML yapısına sahip bir içerik döndürmemesi olasıdır. Bu durumda, durumu incelemek için yanıtın içeriğini yazdırabilirsiniz.
-
Gereksinimler ve Hatalar: Hata içeriğine göz atarak (örneğin, 404 gibi HTTP hatalarını kontrol ederek) yanlış URL'ler veya sunucu yanıtını kontrol edebilirsiniz.
Önerilen değişiklikleri yaparak hatanın kaynağını bulalım.
fetch_rss_datafonksiyonunuza birkaç satır ekleyin:def fetch_rss_data(rss_url, num_items): headers = {'User-Agent': 'Mozilla/5.0'} response = requests.get(rss_url, headers=headers) # Yanıt kodunu kontrol et if response.status_code != 200: st.error(f"Hata: {response.status_code}. Yanıt alınamadı, lütfen URL'yi kontrol edin.") return [] rss_content = response.text # Gelen içerği kontrol et if not rss_content.strip(): # İçerik boşsa hata verebilir st.error("Hata: Boş içerik döndürüldü. URL'yi kontrol edin.") return [] try: # RSS XML'ini parse et root = ET.fromstring(rss_content) except ET.ParseError as e: st.error(f"XML Parse Hatası: {str(e)}") return [] items = root.findall('.//item') news_data = [] # ... (Kalan kod)Bu ekleme, birleşik bir hata kontrolü sağlar. Ayrıca, yanıtın içeriğini boş olup olmadığını da kontrol eder. Eğer yukarıdaki değişiklikleri yaptıktan sonra hala bir sorun yaşıyorsanız, lütfen hata mesajlarını gözden geçirin ve yanıt içeriğini incelemek için yanıtı yazdırmayı düşünün. Örneğin:
print(rss_content) # Yanıt içeriğini konsola yazdırBu şekilde, daha fazla bilgi ile sorunun kaynağına ulaşabilirsiniz.
-
- User
requests.exceptions.ReadTimeout: This app has encountered an error. The original error message is redacted to prevent data leaks. Full error details have been recorded in the logs (if you're on Streamlit Cloud, click on 'Manage app' in the lower right of your app). Traceback: File "/mount/src/autopostcreator/autopostcreator.py", line 214, in create_zip_from_posts(df, output_zip_path, logo_position) File "/mount/src/autopostcreator/autopostcreator.py", line 138, in create_zip_from_posts post_filename = create_post(title, description, img_url, output_folder, title_font, description_font, title_bg_color, description_bg_color, title_text_color, description_text_color, logo, logo_position) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/mount/src/autopostcreator/autopostcreator.py", line 79, in create_post response = requests.get(default_image_url, headers=headers, timeout=10) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/adminuser/venv/lib/python3.12/site-packages/requests/api.py", line 73, in get return request("get", url, params=params, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/adminuser/venv/lib/python3.12/site-packages/requests/api.py", line 59, in request return session.request(method=method, url=url, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/adminuser/venv/lib/python3.12/site-packages/requests/sessions.py", line 589, in request resp = self.send(prep, **send_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/adminuser/venv/lib/python3.12/site-packages/requests/sessions.py", line 703, in send r = adapter.send(request, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/adminuser/venv/lib/python3.12/site-packages/requests/adapters.py", line 713, in send raise ReadTimeout(e, request=request)
- Assistant
Aldığınız hata
requests.exceptions.ReadTimeouthatasıdır. Bu, belirli bir süre içerisinde istemcinin (yani sizin uygulamanızın) sunucu tarafından yanıt alınamadığını gösterir. Hata genellikle yavaş yanıt veren bir sunucu veya ağ sorunları gibi çeşitli nedenlerden kaynaklanabilir.Bu hatayı çözmek için aşağıdaki yöntemleri deneyebilirsiniz:
-
Timeout Süresini Uzatın: Şu anda
requests.getçağrılarında zaman aşımını 10 saniye olarak ayarlamışsınız. Bu süreyi artırarak bir deneme yapabilirsiniz. Örneğin:response = requests.get(default_image_url, headers=headers, timeout=30) # 30 saniye -
Bağlantı Kontrolü: Sunucu yanıt vermiyorsa veya zaman zaman yavaşsa, bu URL'yi tarayıcıda kontrol edin veya başka bir ağ bağlantısında deneyin. Yanıt alınamayan veya yanlış olan bir URL varsa, yanıtı kontrol edin.
-
Başka URL Deneyin: Eğer kullandığınız
default_image_url(örneğin,https://via.placeholder.com/1080) sunucusu zaman zaman yanıt vermiyorsa, başka bir URL ile test etmeyi deneyin. -
Hata Yönetimini İyileştirme: Hata yönetimi kısmını geliştirebilirsiniz. Eğer
ReadTimeouthatası alırsanız, bir geri dönüş mekanizması ekleyebilirsiniz:try: response = requests.get(default_image_url, headers=headers, timeout=30) except requests.exceptions.ReadTimeout: st.error("Görsel yüklenirken zaman aşımına uğradı. Varsayılan görsel kullanılıyor.") # Varsayılan görsel yüklemek için başka bir amaç hedefleyebilirsiniz. -
Geri Dönüş URL'si Kullanma: Bir diğer alternatif olarak, ağ bağlantısı sorunları ile karşılaştığınızda başka bir
default_image_urlkullanabilirsiniz. Örneğin, bir CDN üzerinden sabit bir görsel almak için başka bir URL belirleyebilirsiniz.
Not: Hala sorun yaşıyorsanız, hata ayıklamak için hata günlüklerini gözden geçirin. Uygulamanızın çalıştığı ortamda bağlantı sorunları veya sunucuda bakım olurken hizmet kesintisi yaşanabilir.
Test uygulamanızı tekrar çalıştırdıktan sonra hata devam ederse, aldığınız yeni hata mesajını burada paylaşırsanız size daha fazla yardımcı olabilirim.
-
- User
Gerekli kütüphaneleri yükleyin
!pip install pandas pillow requests !apt-get install -y ttf-mscorefonts-installer
import requests import xml.etree.ElementTree as ET import pandas as pd from PIL import Image, ImageDraw, ImageFont, UnidentifiedImageError from io import BytesIO import re import textwrap import zipfile import os from google.colab import files # Dosya yükleme için
Kullanıcıdan gerekli bilgileri alma
rss_url = input("RSS adresini girin: ") news_count = int(input("Çekmek istediğiniz haber sayısını girin: "))
Kullanıcıdan yazı fontunu yüklemesini isteyin
print("Yazı fontunu yükleyin (TTF formatında):") uploaded_font = files.upload() # Kullanıcının font dosyasını yüklemesini sağlar font_path = next(iter(uploaded_font)) # Yüklenen font dosyasının adını al
Kullanıcıdan logo yüklemesini isteyin
print("Logo dosyasını yükleyin (PNG formatında veya başka bir format):") uploaded_logo = files.upload() # Kullanıcının logo dosyasını yüklemesini sağlar logo_path = next(iter(uploaded_logo)) # Yüklenen logo dosyasının adını al
RSS'den veri çekme fonksiyonu
def fetch_rss_data(rss_url, num_items): headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36' } response = requests.get(rss_url, headers=headers) rss_content = response.text
# RSS XML'ini parse et root = ET.fromstring(rss_content) items = root.findall('.//item') news_data = [] for item in items[:num_items]: title = item.find('.//title').text if item.find('.//title') is not None else 'Başlık Yok' description = item.find('.//description').text if item.find('.//description') is not None else 'Açıklama Yok' # Görsel URL'sini alma image_url = None # 1. <image> etiketi image_tag = item.find('.//image') if image_tag is not None: image_url = image_tag.text # 2. <imageUrl> etiketi if not image_url: image_tag = item.find('.//imageUrl') if image_tag is not None: image_url = image_tag.text # 3. <media:content> etiketi if not image_url: media_content_tag = item.find('.//media:content', namespaces={'media': 'http://search.yahoo.com/mrss/'}) if media_content_tag is not None and 'url' in media_content_tag.attrib: image_url = media_content_tag.attrib['url'] # 4. <enclosure> etiketi if not image_url: enclosure_tag = item.find('.//enclosure') if enclosure_tag is not None and 'url' in enclosure_tag.attrib: image_url = enclosure_tag.attrib['url'] # Sonuç listesine ekle news_data.append((title, description, image_url)) return news_dataRSS verisini çek
data = fetch_rss_data(rss_url, news_count)
Pandas DataFrame oluştur
df = pd.DataFrame(data, columns=['Title', 'Description', 'Image URL'])
CSV dosyasına kaydet
csv_file_path = '/content/yalova.csv' df.to_csv(csv_file_path, index=False)
CSV dosyasının kaydedildiğini göster
print(f"{news_count} haber başarıyla çekildi ve CSV dosyasına kaydedildi: {csv_file_path}")
Font ve boyut ayarları
title_font_size = 35 description_font_size = 25 title_font = ImageFont.truetype(font_path, title_font_size) description_font = ImageFont.truetype(font_path, description_font_size)
Instagram gönderisi için 1080x1080 boyutunda bir kare oluşturur.
post_size = (1080, 1080)
Logo dosyasını yükle
logo_size = (120, 120) logo = Image.open(logo_path).resize(logo_size)
def wrap_text(text, width): lines = textwrap.wrap(text, width=width) return "\n".join(lines)
def create_post(title, description, img_url, output_folder): headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36', 'Referer': 'https://yalovagazetesi.com' } default_image_url = "/content/3d-success-text-perspective-with-words_93487-102.avif"
try: response = requests.get(img_url, headers=headers, timeout=10) response.raise_for_status() if "image" not in response.headers.get("Content-Type", ""): print(f"Bu URL bir resim içermiyor: {img_url}") response = requests.get(default_image_url, headers=headers, timeout=10) except Exception as e: print(f"Resim indirilemedi: {img_url} - Hata: {e}. Varsayılan görsel kullanılacak.") response = requests.get(default_image_url, headers=headers, timeout=10) try: img = Image.open(BytesIO(response.content)) except UnidentifiedImageError: print(f"Varsayılan görsel de yüklenemedi: {default_image_url}") return None img = img.resize(post_size) draw = ImageDraw.Draw(img) title = wrap_text(title, 50).upper() description = wrap_text(description, 80).upper() title_bbox = draw.textbbox((0, 0), title, font=title_font) description_bbox = draw.textbbox((0, 0), description, font=description_font) title_width, title_height = title_bbox[2] - title_bbox[0], title_bbox[3] - title_bbox[1] description_width, description_height = description_bbox[2] - description_bbox[0], description_bbox[3] - description_bbox[1] title_x = 30 description_x = 30 total_height = title_height + description_height title_y = (post_size[1] - total_height) / 2 + 280 description_y = title_y + title_height + 70 draw.rectangle([title_x - 20, title_y - 20, title_width + title_x + 20, title_y + title_height + 20], fill=(0, 107, 107)) draw.rectangle([description_x - 20, description_y - 20, description_width + description_x + 20, description_y + description_height + 20], fill=(255, 255, 255)) draw.text((title_x, title_y), title, font=title_font, fill=(255, 255, 255)) draw.text((description_x, description_y), description, font=description_font, fill=(0, 0, 0)) img.paste(logo, (post_size[0] - logo_size[0] - 30, 30), logo) safe_title = re.sub(r'[^\w\-_\. ]', '_', title[:10]) post_filename = os.path.join(output_folder, f"post_{safe_title}.jpg") img.save(post_filename) return post_filenameKullanılacak CSV dosyaları
csv_files = [ (csv_file_path, "posts_yalova.zip"), ]
Her bir CSV dosyası için işlem yapar
for csv_file, zip_filename in csv_files: output_folder = f"/content/posts_{os.path.splitext(os.path.basename(csv_file))[0]}" os.makedirs(output_folder, exist_ok=True)
df = pd.read_csv(csv_file) with zipfile.ZipFile(f"/content/{zip_filename}", 'w') as zipf: for index, row in df.iterrows(): title = row['Title'] description = row['Description'] img_url = row['Image URL'] try: post_filename = create_post(title, description, img_url, output_folder) if post_filename: zipf.write(post_filename, os.path.basename(post_filename)) os.remove(post_filename) except Exception as e: print(f"Hata oluştu: {e}") print(f"{zip_filename} dosyası oluşturuldu.")Tüm ZIP dosyalarını indirilebilir hale getir
for _, zip_filename in csv_files: files.download(f"/content/{zip_filename}") bu kod ile google colabta aynı rss adresınden ıslem yapabılıyorum faakt
import requests import xml.etree.ElementTree as ET import pandas as pd from PIL import Image, ImageDraw, ImageFont, UnidentifiedImageError import zipfile import os from io import BytesIO import re import html import textwrap import streamlit as st
RSS'den veri çekme fonksiyonu
def fetch_rss_data(rss_url, num_items): headers = {'User-Agent': 'Mozilla/5.0'} response = requests.get(rss_url, headers=headers)
# Yanıt kodunu kontrol et if response.status_code != 200: st.error(f"Hata: {response.status_code}. Yanıt alınamadı, lütfen URL'yi kontrol edin.") return [] rss_content = response.text # Gelen içerği kontrol et if not rss_content.strip(): # İçerik boşsa hata verebilir st.error("Hata: Boş içerik döndürüldü. URL'yi kontrol edin.") return [] try: # RSS XML'ini parse et root = ET.fromstring(rss_content) except ET.ParseError as e: st.error(f"XML Parse Hatası: {str(e)}") return [] items = root.findall('.//item') news_data = [] items = root.findall('.//item') news_data = [] for item in items[:num_items]: title = item.find('.//title').text if item.find('.//title') is not None else 'Başlık Yok' description = item.find('.//description').text if item.find('.//description') is not None else 'Açıklama Yok' # CDATA etiketlerini temizleme description = re.sub(r'<!\[CDATA\[(.*?)\]\]>', r'\1', description) description = html.unescape(description) # Görsel URL'sini alma image_url = None image_tag = item.find('.//image') or item.find('.//imageUrl') or \ item.find('.//media:content', namespaces={'media': 'http://search.yahoo.com/mrss/'}) or \ item.find('.//enclosure') if image_tag is not None and 'url' in image_tag.attrib: image_url = image_tag.attrib['url'] if image_tag.tag == 'enclosure' and 'url' in image_tag.attrib else image_tag.text news_data.append((title, description, image_url)) return news_dataGörsel oluşturma fonksiyonu
def wrap_text(text, width): lines = textwrap.wrap(text, width=width) return "\n".join(lines)
def create_post(title, description, img_url, output_folder, title_font, description_font, title_bg_color, description_bg_color, title_text_color, description_text_color, logo, logo_position): headers = {'User-Agent': 'Mozilla/5.0'} default_image_url = "https://via.placeholder.com/1080" # Varsayılan bir görsel URL'si
try: response = requests.get(img_url, headers=headers, timeout=10) response.raise_for_status() if "image" not in response.headers.get("Content-Type", ""): response = requests.get(default_image_url, headers=headers, timeout=10) except Exception: response = requests.get(default_image_url, headers=headers, timeout=10) try: img = Image.open(BytesIO(response.content)) except UnidentifiedImageError: return None img = img.resize((1080, 1080)) draw = ImageDraw.Draw(img) wrapped_title = wrap_text(title, 50).upper() wrapped_description = wrap_text(description, 80).upper() title_bbox = draw.textbbox((0, 0), wrapped_title, font=title_font) description_bbox = draw.textbbox((0, 0), wrapped_description, font=description_font) title_width, title_height = title_bbox[2] - title_bbox[0], title_bbox[3] - title_bbox[1] description_width, description_height = description_bbox[2] - description_bbox[0], description_bbox[3] - description_bbox[1] # Başlık konumunu ayarlama title_x = 30 if title_alignment == "Sol" else 1080 - title_width - 30 description_x = 30 if description_alignment == "Sol" else 1080 - description_width - 30 total_height = title_height + description_height title_y = (1080 - total_height) / 2 + 280 description_y = title_y + title_height + 70 # Oval kutular oluşturma corner_radius = 20 # Oval köşe yarıçapı draw.rounded_rectangle([title_x - 20, title_y - 20, title_width + title_x + 20, title_y + title_height + 20], radius=corner_radius, fill=title_bg_color) draw.rounded_rectangle([description_x - 20, description_y - 20, description_width + description_x + 20, description_y + description_height + 20], radius=corner_radius, fill=description_bg_color) draw.text((title_x, title_y), wrapped_title, font=title_font, fill=title_text_color) draw.text((description_x, description_y), wrapped_description, font=description_font, fill=description_text_color) logo_resized = logo.resize((logo_size, logo_size)) if logo_position == "Sol Üst": logo_x, logo_y = 30, 30 else: # Sağ Üst logo_x, logo_y = 1080 - logo_size - 30, 30 img.paste(logo_resized, (logo_x, logo_y), logo_resized) safe_title = re.sub(r'[^\w\-_\. ]', '_', title[:10]) post_filename = os.path.join(os.path.dirname(output_folder), f"post_{safe_title}.jpg") os.makedirs(os.path.dirname(output_folder), exist_ok=True) img.save(post_filename) return post_filenameZIP dosyasını oluşturma ve indirme fonksiyonu
def create_zip_from_posts(csv_data, output_folder, logo_position): with zipfile.ZipFile(output_folder, 'w') as zipf: for index, row in csv_data.iterrows(): title = row['Title'] description = row['Description'] img_url = row['Image URL']
post_filename = create_post(title, description, img_url, output_folder, title_font, description_font, title_bg_color, description_bg_color, title_text_color, description_text_color, logo, logo_position) if post_filename: zipf.write(post_filename, os.path.basename(post_filename)) os.remove(post_filename)Streamlit UI ile işlemi başlatma
st.title("Auto Post Creator") rss_url = st.text_input("RSS adresini girin:") news_count = st.number_input("istediğiniz Post sayısını girin:", min_value=1, step=1)
Logo konumu ve dosya yükleme
logo_position = st.selectbox("Logonun konumunu seçin:", options=["Sol Üst", "Sağ Üst"]) uploaded_font = st.file_uploader("Yazı fontunu yükleyin (TTF formatında)", type=["ttf"]) uploaded_logo = st.file_uploader("Logo dosyasını yükleyin (PNG formatında)", type=["png", "jpg", "jpeg"])
Kutu ve metin renkleri
title_bg_color = st.color_picker("Başlık arka plan rengini seçin:", "#009999") description_bg_color = st.color_picker("Açıklama arka plan rengini seçin:", "#FFFFFF") title_text_color = st.color_picker("Başlık metni rengini seçin:", "#FFFFFF") description_text_color = st.color_picker("Açıklama metni rengini seçin:", "#000000")
Font boyutlarını ayarlama
title_font_size = st.number_input("Başlık font boyutunu ayarlayın:", min_value=10, max_value=100, value=35) description_font_size = st.number_input("Açıklama font boyutunu ayarlayın:", min_value=10, max_value=100, value=25)
Metin konumu ayarlama için seçim aracı
title_alignment = st.selectbox("Başlık konumunu seçin:", options=["Sol", "Sağ"]) description_alignment = st.selectbox("Açıklama konumunu seçin:", options=["Sol", "Sağ"])
Logo boyutunu sabit olarak belirleme
logo_size = 150 # Logo boyutu: 150x150
Yardım Dokümanları
st.sidebar.header("Yardım") st.sidebar.write(""" Uygulama Rehberi:
- RSS adresi girin ve kaç post oluşturmak istediğinizi seçin.
- Logo ve font dosyalarınızı yükleyin.
- Başlık / açıklama konumlarını ve renklerini ayarlayın.
- En uygun FONT "Avgardd TTF" fontudur.
- Tercihinize göre farklı fontlar ve font boyutlar deneyerek değişikler yapabilirsiniz.
- "Gönder" butonuna basarak gerekli işlemleri tamamlayın. """)
if st.button('Gönder'): if rss_url and uploaded_font and uploaded_logo: # ZIP dosyası için dizini belirleme zip_dir = os.path.join(os.path.expanduser("~"), "Desktop", "post") os.makedirs(zip_dir, exist_ok=True) # Dizin yoksa oluştur
# ZIP dosyasının tam yolunu belirleme output_zip_path = os.path.join(zip_dir, "posts.zip") # RSS verilerini al data = fetch_rss_data(rss_url, news_count) if data: df = pd.DataFrame(data, columns=['Title', 'Description', 'Image URL']) # Fontu yükleme title_font = None description_font = None if uploaded_font: try: font_bytes = uploaded_font.read() title_font = ImageFont.truetype(BytesIO(font_bytes), title_font_size) description_font = ImageFont.truetype(BytesIO(font_bytes), description_font_size) except Exception as e: st.error(f"Font yüklenirken bir hata oluştu: {e}") # Logo dosyasını yükleme logo = None if uploaded_logo: logo = Image.open(uploaded_logo) # ZIP dosyasının oluşturulması create_zip_from_posts(df, output_zip_path, logo_position) # ZIP dosyasını oku ve akışa yaz with open(output_zip_path, 'rb') as f: st.download_button("ZIP Dosyasını İndir", data=f, file_name="posts.zip", mime="application/zip") else: st.error("Hatalı RSS URL veya veri bulunamadı.") else: st.error("Lütfen tüm alanları doldurun: RSS URL, Font, Logo.") bu kod ıle aldıgım hatarequests.exceptions.ReadTimeout: This app has encountered an error. The original error message is redacted to prevent data leaks. Full error details have been recorded in the logs (if you're on Streamlit Cloud, click on 'Manage app' in the lower right of your app). Traceback: File "/mount/src/autopostcreator/autopostcreator.py", line 214, in create_zip_from_posts(df, output_zip_path, logo_position) File "/mount/src/autopostcreator/autopostcreator.py", line 138, in create_zip_from_posts post_filename = create_post(title, description, img_url, output_folder, title_font, description_font, title_bg_color, description_bg_color, title_text_color, description_text_color, logo, logo_position) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/mount/src/autopostcreator/autopostcreator.py", line 79, in create_post response = requests.get(default_image_url, headers=headers, timeout=10) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/adminuser/venv/lib/python3.12/site-packages/requests/api.py", line 73, in get return request("get", url, params=params, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/adminuser/venv/lib/python3.12/site-packages/requests/api.py", line 59, in request return session.request(method=method, url=url, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/adminuser/venv/lib/python3.12/site-packages/requests/sessions.py", line 589, in request resp = self.send(prep, **send_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/adminuser/venv/lib/python3.12/site-packages/requests/sessions.py", line 703, in send r = adapter.send(request, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/adminuser/venv/lib/python3.12/site-packages/requests/adapters.py", line 713, in send raise ReadTimeout(e, request=request)
- Assistant
Aldığınız
requests.exceptions.ReadTimeouthatası, belirli bir süre içinde sunucudan yanıt alamadığınız anlamına gelir. Bu durum genellikle kötü ağ bağlantısı veya yanıt vermeyen bir sunucu nedeniyle meydana gelir. Uygulamanızın çalıştığı ortamı göz önünde bulundurarak aşağıdaki adımları takip edebilirsiniz:1. Timeout Süresini Uzatın
Şu anda
requests.get(default_image_url, headers=headers, timeout=10)kullanıyorsunuz. Timeout süresini artırmayı deneyin. Örneğin:response = requests.get(default_image_url, headers=headers, timeout=30) # 30 saniye2. Alternatif Görsel URL'leri Deneyin
Varsayılan görsel URL'niz
https://via.placeholder.com/1080kullanılabilir ve genelde sağlam olmalıdır. Ancak, farklı bir URL kullanmayı deneyin. Örneğin:default_image_url = "https://via.placeholder.com/1080/009999/FFFFFF?text=Default+Image"3. Hata Yönetimini Geliştirin
Hataları daha iyi yönetmek için
try-exceptbloklarını iyileştirebilirsiniz. Örneğin, yalnızca bir hata durumunda varsayılan görseli almak yerine, yanıtın otomatik olarak süresinin dolması durumunda da başka bir görsel URL'sine yönlenin.def create_post(title, description, img_url, output_folder, title_font, description_font, title_bg_color, description_bg_color, title_text_color, description_text_color, logo, logo_position): headers = {'User-Agent': 'Mozilla/5.0'} default_image_url = "https://via.placeholder.com/1080" try: response = requests.get(img_url, headers=headers, timeout=10) response.raise_for_status() except requests.exceptions.Timeout: st.warning(f"{img_url} için zaman aşımı. Varsayılan görsel kullanılacak.") response = requests.get(default_image_url, headers=headers, timeout=10) except requests.exceptions.RequestException as e: st.error(f"Resim indirilemedi: {img_url} - Hata: {str(e)}. Varsayılan görsel kullanılacak.") response = requests.get(default_image_url, headers=headers, timeout=10) # Görseli açma ve kaydetme işlemleri...4. Ağ Bağlantısını Kontrol Edin
Çalıştığınız ortamda (örneğin, Streamlit Cloud veya başka bir bulut hizmeti) ağın istikrarlı olduğundan emin olun. Bazı durumlarda, bulut hizmetleri, belirli ağ sınırlamalarına sahip olabilir, bu da dış kaynaklarla (örneğin, görsel URL'leri) iletişim kurmakta zorluk yaratabilir.
5. Hata Günlüğünü Kontrol Edin
Streamlit uygulamanız hata kayıtlarını sağla, böylece sorunun daha derinlemesine analizi yapılabilir. Hangi URL'nin yüklenmediğini belirlemek için daha ayrıntılı bir hata raporu alabilirsiniz.
6. Düzenli Testler Yapın
Kodunuzun her bölümünü düzenli olarak test edin. Farklı görsel URL'leri ile test yaparak, herhangi bir zaman aşımı hatası olup olmadığını kontrol edin.
Eğer yukarıdaki yöntemleri uyguladıktan sonra hala sorun yaşıyorsanız lütfen yeni hatalar veya mesajlar ile geri dönün; böylece daha spesifik çözümler sunabilirim.