chalet_jornal / content_automation.py
Medon90ae's picture
Update content_automation.py
8475abd verified
import pandas as pd
import datetime
import os
import time
from data_collection import extract_tourism_trends, scrape_chalets_from_web
from content_creation import generate_tourism_article, extract_keywords, generate_article_title, generate_meta_description
from content_analysis import analyze_content_readability, analyze_sentiment, improve_content, analyze_content_completeness
from performance_analysis import add_performance_record
def automated_content_creation(chalet_data, style="informative", target_audience="عام"):
"""
إنشاء محتوى متكامل بشكل آلي لشاليه محدد
"""
try:
# 1. إنشاء المقال
article = generate_tourism_article(chalet_data, style)
# 2. إنشاء عنوان للمقال
title = generate_article_title(chalet_data, style)
# 3. إنشاء وصف تعريفي
meta_description = generate_meta_description(chalet_data, style)
# 4. استخراج الكلمات المفتاحية
keywords = extract_keywords(article)
# 5. تحليل المحتوى
readability = analyze_content_readability(article)
sentiment = analyze_sentiment(article)
completeness = analyze_content_completeness(article, chalet_data)
# 6. تحسين المحتوى
improvements = improve_content(article, target_audience)
# 7. تطبيق التحسينات إذا كانت هناك اقتراحات
improved_article = article
if improvements['improvements']:
# هنا يمكن إضافة منطق لتطبيق التحسينات تلقائيًا
# لكن في هذه المرحلة سنكتفي بالإشارة إلى وجود اقتراحات
pass
# 8. حفظ المحتوى
content_id = f"{chalet_data['name'].replace(' ', '_')}_{style}_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}"
save_path = save_automated_content(title, meta_description, improved_article, keywords, content_id)
# 9. إضافة سجل أداء أولي
add_performance_record(content_id, style, 0, 0, 0, datetime.datetime.now().strftime("%Y-%m-%d"))
return {
"content_id": content_id,
"title": title,
"meta_description": meta_description,
"article": improved_article,
"keywords": keywords,
"analysis": {
"readability": readability,
"sentiment": sentiment,
"completeness": completeness,
"improvements": improvements
},
"save_path": save_path
}
except Exception as e:
print(f"خطأ في إنشاء المحتوى التلقائي: {str(e)}")
return None
def save_automated_content(title, meta_description, article, keywords, content_id):
"""
حفظ المحتوى المنشأ تلقائيًا
"""
try:
# إنشاء مجلد للمحتوى المؤتمت إذا لم يكن موجودًا
if not os.path.exists("automated_content"):
os.makedirs("automated_content")
# إنشاء اسم الملف
filename = f"automated_content/{content_id}.txt"
# حفظ المحتوى
with open(filename, 'w', encoding='utf-8') as f:
f.write(f"{title}\n\n")
f.write(f"{meta_description}\n\n")
f.write(article)
f.write("\n\nالكلمات المفتاحية: " + ", ".join(keywords))
return filename
except Exception as e:
print(f"خطأ في حفظ المحتوى المؤتمت: {str(e)}")
return None
def batch_content_creation(chalets_data, style="informative", target_audience="عام"):
"""
إنشاء محتوى متكامل لمجموعة من الشاليهات
"""
results = []
for _, chalet_data in chalets_data.iterrows():
result = automated_content_creation(chalet_data.to_dict(), style, target_audience)
if result:
results.append(result)
# إضافة تأخير لتجنب الضغط على الخوادم
time.sleep(2)
return results
def schedule_content_creation(schedule_type="daily", hour=9, minute=0):
"""
جدولة إنشاء المحتوى بشكل دوري (نسخة بسيطة بدون مكتبة schedule)
"""
# تعريف المهمة التي كانت ستنفذ في الجدولة
def job():
print(f"بدء إنشاء المحتوى المجدول في {datetime.datetime.now()}")
# 1. جمع بيانات الشاليهات
chalets = scrape_chalets_from_web()
if chalets:
df = pd.DataFrame(chalets)
# 2. إنشاء محتوى لكل شاليه
results = batch_content_creation(df)
print(f"تم إنشاء {len(results)} مقال بنجاح")
return results
else:
print("لم يتم العثور على أي بيانات للشاليهات")
return []
# إرجاع معلومات عن الجدولة المطلوبة
schedule_info = {
"type": schedule_type,
"hour": hour,
"minute": minute,
"formatted_time": f"{hour:02d}:{minute:02d}",
"job": job # إرجاع المهمة نفسها كدالة يمكن استدعاؤها
}
print(f"تم تجهيز إنشاء المحتوى {schedule_type} في الساعة {hour:02d}:{minute:02d}")
# تنفيذ المهمة مباشرة إذا طلب المستخدم ذلك
return schedule_info
def create_content_for_trending_topics():
"""
إنشاء محتوى يتعلق بالمواضيع الرائجة
"""
try:
# 1. استخراج اتجاهات السياحة
trends = extract_tourism_trends()
# 2. جمع بيانات الشاليهات
chalets = scrape_chalets_from_web()
if not chalets:
print("لم يتم العثور على أي بيانات للشاليهات")
return []
df = pd.DataFrame(chalets)
# 3. إنشاء محتوى يربط بين الاتجاهات والشاليهات
results = []
for trend in trends[:5]: # اختيار أهم 5 اتجاهات
# البحث عن شاليهات ذات صلة بالاتجاه
related_chalets = df[df['description'].str.contains(trend['title'], case=False, na=False)]
if not related_chalets.empty:
# اختيار أول شاليه ذي صلة
chalet_data = related_chalets.iloc[0].to_dict()
# إنشاء محتوى يربط بين الشاليه والاتجاه
result = automated_content_creation(chalet_data, "informative", "عام")
if result:
results.append(result)
return results
except Exception as e:
print(f"خطأ في إنشاء محتوى للمواضيع الرائجة: {str(e)}")
return []