+
+**🚀 ساخته شده با ❤️ برای جامعه محتواسازان ایرانی**
-© 2023 GitHub • [Code of Conduct](https://www.contributor-covenant.org/version/2/1/code_of_conduct/code_of_conduct.md) • [MIT License](https://gh.io/mit)
+[](https://python.org)
+[](https://fastapi.tiangolo.com)
+[](LICENSE)
+[](README.md)
-
+
\ No newline at end of file
diff --git a/examples/sample_requests.py b/examples/sample_requests.py
new file mode 100644
index 0000000..b0dfee9
--- /dev/null
+++ b/examples/sample_requests.py
@@ -0,0 +1,244 @@
+"""
+نمونههای استفاده از سیستم تولید محتوای هوش مصنوعی
+"""
+
+import requests
+import json
+from datetime import datetime, timedelta
+
+# آدرس سرور (در صورت اجرا در محیط محلی)
+BASE_URL = "http://localhost:8000/api"
+
+def example_generate_content():
+ """نمونه تولید محتوا برای چند پلتفرم"""
+
+ payload = {
+ "topic": "فواید یادگیری هوش مصنوعی",
+ "keywords": ["هوش مصنوعی", "یادگیری ماشین", "فناوری", "آینده"],
+ "platforms": ["instagram", "telegram", "website"],
+ "content_type": "post",
+ "tone": "educational",
+ "target_audience": "دانشجویان و علاقهمندان فناوری"
+ }
+
+ response = requests.post(f"{BASE_URL}/generate-content", json=payload)
+
+ if response.status_code == 200:
+ result = response.json()
+
+ print("✅ محتوا با موفقیت تولید شد!")
+ print(f"📊 تعداد پلتفرمها: {result['total_platforms']}")
+ print(f"🕐 زمان تولید: {result['generated_at']}")
+
+ # نمایش محتوا برای هر پلتفرم
+ for platform, content in result['contents'].items():
+ print(f"\n📱 {platform.upper()}:")
+ print("-" * 50)
+ if isinstance(content, dict):
+ print(content['content'])
+ print(f"📏 تعداد کاراکتر: {content.get('character_count', 0)}")
+ print(f"⭐ امتیاز جذابیت: {content.get('engagement_score', 0)}/10")
+ else:
+ print(content)
+
+ # نمایش هشتگها
+ print(f"\n🏷️ هشتگهای پیشنهادی:")
+ for platform, hashtags in result['hashtags'].items():
+ print(f"{platform}: {' '.join(hashtags[:5])}")
+
+ # نمایش پیشنهادات CTA
+ print(f"\n📢 پیشنهادات فراخوان عمل:")
+ for cta in result['cta_suggestions'][:3]:
+ print(f"• {cta}")
+
+ return result
+ else:
+ print(f"❌ خطا: {response.status_code}")
+ print(response.text)
+
+def example_optimize_seo():
+ """نمونه بهینهسازی SEO"""
+
+ sample_text = """
+ هوش مصنوعی یکی از مهمترین فناوریهای قرن حاضر است.
+ این فناوری در حال تغییر دادن دنیای ما است و کاربردهای فراوانی دارد.
+ یادگیری ماشین بخش مهمی از هوش مصنوعی محسوب میشود.
+ """
+
+ payload = {
+ "text": sample_text,
+ "target_keywords": ["هوش مصنوعی", "یادگیری ماشین", "فناوری"],
+ "focus_keyword": "هوش مصنوعی",
+ "meta_description": "راهنمای جامع هوش مصنوعی و کاربردهای آن"
+ }
+
+ response = requests.post(f"{BASE_URL}/optimize-seo", json=payload)
+
+ if response.status_code == 200:
+ result = response.json()
+
+ print("✅ بهینهسازی SEO انجام شد!")
+ print(f"🎯 امتیاز SEO: {result['seo_score']}/100")
+ print(f"📖 امتیاز خوانایی: {result['readability_score']}/100")
+ print(f"📝 تعداد کلمات: {result['word_count']}")
+
+ print(f"\n📊 تراکم کلمات کلیدی:")
+ for keyword, density in result['keywords_density'].items():
+ print(f"• {keyword}: {density}%")
+
+ print(f"\n💡 توصیههای بهبود:")
+ for recommendation in result['recommendations'][:5]:
+ print(f"• {recommendation}")
+
+ return result
+ else:
+ print(f"❌ خطا: {response.status_code}")
+ print(response.text)
+
+def example_generate_visual_ideas():
+ """نمونه تولید ایدههای بصری"""
+
+ sample_content = """
+ ۵ نکته طلایی برای شروع یادگیری هوش مصنوعی:
+ 1. پایههای ریاضی را تقویت کنید
+ 2. زبان برنامهنویسی Python یاد بگیرید
+ 3. با کتابخانههای معروف آشنا شوید
+ 4. پروژههای عملی انجام دهید
+ 5. در جامعه فعال باشید
+ """
+
+ payload = {
+ "content": sample_content,
+ "platform": "instagram",
+ "content_type": "post",
+ "style_preferences": ["modern", "colorful"]
+ }
+
+ response = requests.post(f"{BASE_URL}/generate-visual-idea", json=payload)
+
+ if response.status_code == 200:
+ result = response.json()
+
+ print("✅ ایدههای بصری تولید شدند!")
+
+ print(f"\n🖼️ ایدههای تصویری:")
+ for i, idea in enumerate(result['image_ideas'], 1):
+ print(f"{i}. سبک: {idea['style']}")
+ print(f" توضیح: {idea['description']}")
+ print(f" چیدمان: {idea['layout']}")
+
+ print(f"\n🎬 ایدههای ویدئویی:")
+ for i, idea in enumerate(result['video_ideas'], 1):
+ print(f"{i}. نوع: {idea['type']}")
+ print(f" مدت: {idea['duration']}")
+ print(f" سبک: {idea['style']}")
+
+ print(f"\n🎨 رنگهای پیشنهادی:")
+ print(" ".join(result['color_suggestions'][:5]))
+
+ return result
+ else:
+ print(f"❌ خطا: {response.status_code}")
+ print(response.text)
+
+def example_schedule_content():
+ """نمونه زمانبندی محتوا"""
+
+ # زمان انتشار: یک ساعت بعد
+ schedule_time = datetime.now() + timedelta(hours=1)
+
+ payload = {
+ "platform": "telegram",
+ "content": "🚀 محتوای تست برای زمانبندی!\n\nاین پست به صورت خودکار منتشر میشود.",
+ "schedule_time": schedule_time.isoformat(),
+ "auto_publish": True
+ }
+
+ response = requests.post(f"{BASE_URL}/schedule-post", json=payload)
+
+ if response.status_code == 200:
+ result = response.json()
+
+ print("✅ محتوا زمانبندی شد!")
+ print(f"🆔 شناسه: {result['schedule_id']}")
+ print(f"⏰ زمان انتشار: {result['scheduled_time']}")
+
+ return result
+ else:
+ print(f"❌ خطا: {response.status_code}")
+ print(response.text)
+
+def example_get_scheduled_posts():
+ """نمونه دریافت پستهای زمانبندی شده"""
+
+ response = requests.get(f"{BASE_URL}/scheduled-posts")
+
+ if response.status_code == 200:
+ posts = response.json()
+
+ print(f"📋 تعداد پستهای زمانبندی شده: {len(posts)}")
+
+ for post in posts[:5]: # نمایش ۵ پست اول
+ print(f"\n🆔 {post['id']}")
+ print(f"📱 پلتفرم: {post['platform']}")
+ print(f"📄 محتوا: {post['content'][:50]}...")
+ print(f"📅 زمان: {post['schedule_time']}")
+ print(f"🔘 وضعیت: {post['status']}")
+
+ return posts
+ else:
+ print(f"❌ خطا: {response.status_code}")
+ print(response.text)
+
+def example_get_stats():
+ """نمونه دریافت آمار سیستم"""
+
+ response = requests.get(f"{BASE_URL}/stats")
+
+ if response.status_code == 200:
+ stats = response.json()
+
+ print("📊 آمار سیستم:")
+ print(f"📝 محتوای تولید شده: {stats.get('total_generated_contents', 0)}")
+ print(f"⏰ زمانبندی شده: {stats.get('scheduled_posts_count', 0)}")
+ print(f"📱 پلتفرمهای فعال: {stats.get('active_platforms', 0)}")
+
+ return stats
+ else:
+ print(f"❌ خطا: {response.status_code}")
+ print(response.text)
+
+def run_all_examples():
+ """اجرای تمام نمونهها"""
+
+ print("🤖 شروع نمایش نمونههای سیستم تولید محتوای هوش مصنوعی")
+ print("=" * 60)
+
+ try:
+ print("\n1️⃣ تولید محتوا:")
+ example_generate_content()
+
+ print("\n2️⃣ بهینهسازی SEO:")
+ example_optimize_seo()
+
+ print("\n3️⃣ تولید ایدههای بصری:")
+ example_generate_visual_ideas()
+
+ print("\n4️⃣ زمانبندی محتوا:")
+ example_schedule_content()
+
+ print("\n5️⃣ دریافت پستهای زمانبندی شده:")
+ example_get_scheduled_posts()
+
+ print("\n6️⃣ آمار سیستم:")
+ example_get_stats()
+
+ except requests.exceptions.ConnectionError:
+ print("❌ خطا: نمیتوان به سرور متصل شد.")
+ print("🔧 لطفاً مطمئن شوید که سرور در حال اجرا است:")
+ print(" python main.py")
+ except Exception as e:
+ print(f"❌ خطای غیرمنتظره: {e}")
+
+if __name__ == "__main__":
+ run_all_examples()
\ No newline at end of file
diff --git a/main.py b/main.py
new file mode 100644
index 0000000..40d875d
--- /dev/null
+++ b/main.py
@@ -0,0 +1,275 @@
+"""
+سیستم تولید محتوای هوش مصنوعی چندپلتفرمی
+نویسنده: AI Content Generator System
+ورژن: 1.0.0
+"""
+
+from fastapi import FastAPI, HTTPException, BackgroundTasks
+from fastapi.middleware.cors import CORSMiddleware
+from fastapi.staticfiles import StaticFiles
+from fastapi.templating import Jinja2Templates
+from fastapi.responses import HTMLResponse
+from fastapi import Request
+from pydantic import BaseModel, Field
+from typing import List, Optional, Dict, Any
+from datetime import datetime, timedelta
+import json
+import asyncio
+import logging
+from enum import Enum
+
+# وارد کردن ماژولهای سیستم
+from src.content_generator import ContentGenerator
+from src.seo_optimizer import SEOOptimizer
+from src.visual_idea_generator import VisualIdeaGenerator
+from src.scheduler import ContentScheduler
+from src.platforms import PlatformType, ContentType
+from src.models import (
+ ContentRequest, ContentResponse,
+ ScheduleRequest, VisualIdeaRequest,
+ SEOOptimizationRequest
+)
+
+# تنظیمات لاگ
+logging.basicConfig(
+ level=logging.INFO,
+ format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
+)
+logger = logging.getLogger(__name__)
+
+# ایجاد اپلیکیشن FastAPI
+app = FastAPI(
+ title="سیستم تولید محتوای هوش مصنوعی",
+ description="سیستم جامع تولید محتوا برای پلتفرمهای مختلف با قابلیت Function Calling",
+ version="1.0.0",
+ docs_url="/docs",
+ redoc_url="/redoc"
+)
+
+# تنظیمات CORS
+app.add_middleware(
+ CORSMiddleware,
+ allow_origins=["*"],
+ allow_credentials=True,
+ allow_methods=["*"],
+ allow_headers=["*"],
+)
+
+# ایجاد نمونههای کلاسها
+content_generator = ContentGenerator()
+seo_optimizer = SEOOptimizer()
+visual_idea_generator = VisualIdeaGenerator()
+scheduler = ContentScheduler()
+
+# تنظیم فایلهای استاتیک و قالبها
+app.mount("/static", StaticFiles(directory="static"), name="static")
+templates = Jinja2Templates(directory="templates")
+
+@app.get("/", response_class=HTMLResponse)
+async def home(request: Request):
+ """صفحه اصلی سیستم"""
+ return templates.TemplateResponse("index.html", {"request": request})
+
+@app.post("/api/generate-content", response_model=ContentResponse)
+async def generate_content_api(request: ContentRequest):
+ """
+ تولید محتوا برای پلتفرمهای مختلف
+
+ Function: generate_content(platform, topic, keywords, tone)
+ """
+ try:
+ logger.info(f"تولید محتوا برای موضوع: {request.topic}")
+
+ # تولید محتوا برای هر پلتفرم
+ contents = {}
+
+ for platform in request.platforms:
+ platform_content = await content_generator.generate_for_platform(
+ platform=platform,
+ topic=request.topic,
+ keywords=request.keywords,
+ tone=request.tone,
+ target_audience=request.target_audience,
+ content_type=request.content_type
+ )
+ contents[platform.value] = platform_content
+
+ # تولید هشتگها
+ hashtags = await content_generator.generate_hashtags(
+ topic=request.topic,
+ keywords=request.keywords,
+ platforms=request.platforms
+ )
+
+ # تولید ایدههای CTA
+ cta_suggestions = await content_generator.generate_cta_suggestions(
+ topic=request.topic,
+ platforms=request.platforms,
+ content_type=request.content_type
+ )
+
+ response = ContentResponse(
+ contents=contents,
+ hashtags=hashtags,
+ cta_suggestions=cta_suggestions,
+ generated_at=datetime.now(),
+ request_id=f"req_{int(datetime.now().timestamp())}"
+ )
+
+ logger.info("محتوا با موفقیت تولید شد")
+ return response
+
+ except Exception as e:
+ logger.error(f"خطا در تولید محتوا: {str(e)}")
+ raise HTTPException(status_code=500, detail=f"خطا در تولید محتوا: {str(e)}")
+
+@app.post("/api/optimize-seo")
+async def optimize_for_seo_api(request: SEOOptimizationRequest):
+ """
+ بهینهسازی محتوا برای SEO
+
+ Function: optimize_for_seo(text, target_keywords)
+ """
+ try:
+ logger.info("شروع بهینهسازی SEO")
+
+ optimized_content = await seo_optimizer.optimize_content(
+ text=request.text,
+ target_keywords=request.target_keywords,
+ meta_description=request.meta_description,
+ focus_keyword=request.focus_keyword
+ )
+
+ logger.info("بهینهسازی SEO با موفقیت انجام شد")
+ return optimized_content
+
+ except Exception as e:
+ logger.error(f"خطا در بهینهسازی SEO: {str(e)}")
+ raise HTTPException(status_code=500, detail=f"خطا در بهینهسازی SEO: {str(e)}")
+
+@app.post("/api/generate-visual-idea")
+async def generate_visual_idea_api(request: VisualIdeaRequest):
+ """
+ تولید ایدههای بصری برای محتوا
+
+ Function: generate_visual_idea(content)
+ """
+ try:
+ logger.info("تولید ایدههای بصری")
+
+ visual_ideas = await visual_idea_generator.generate_ideas(
+ content=request.content,
+ platform=request.platform,
+ content_type=request.content_type,
+ style_preferences=request.style_preferences
+ )
+
+ logger.info("ایدههای بصری با موفقیت تولید شدند")
+ return visual_ideas
+
+ except Exception as e:
+ logger.error(f"خطا در تولید ایدههای بصری: {str(e)}")
+ raise HTTPException(status_code=500, detail=f"خطا در تولید ایدههای بصری: {str(e)}")
+
+@app.post("/api/schedule-post")
+async def schedule_post_api(request: ScheduleRequest, background_tasks: BackgroundTasks):
+ """
+ زمانبندی انتشار محتوا
+
+ Function: schedule_post(platform, datetime)
+ """
+ try:
+ logger.info(f"زمانبندی انتشار برای {request.platform.value}")
+
+ schedule_id = await scheduler.schedule_content(
+ platform=request.platform,
+ content=request.content,
+ schedule_time=request.schedule_time,
+ auto_publish=request.auto_publish
+ )
+
+ # اضافه کردن به تسکهای پسزمینه
+ if request.auto_publish:
+ background_tasks.add_task(
+ scheduler.execute_scheduled_post,
+ schedule_id
+ )
+
+ logger.info(f"محتوا با شناسه {schedule_id} زمانبندی شد")
+ return {
+ "message": "محتوا با موفقیت زمانبندی شد",
+ "schedule_id": schedule_id,
+ "scheduled_time": request.schedule_time
+ }
+
+ except Exception as e:
+ logger.error(f"خطا در زمانبندی: {str(e)}")
+ raise HTTPException(status_code=500, detail=f"خطا در زمانبندی: {str(e)}")
+
+@app.get("/api/scheduled-posts")
+async def get_scheduled_posts():
+ """دریافت لیست پستهای زمانبندی شده"""
+ try:
+ scheduled_posts = await scheduler.get_scheduled_posts()
+ return scheduled_posts
+ except Exception as e:
+ logger.error(f"خطا در دریافت پستهای زمانبندی شده: {str(e)}")
+ raise HTTPException(status_code=500, detail=str(e))
+
+@app.delete("/api/scheduled-posts/{schedule_id}")
+async def cancel_scheduled_post(schedule_id: str):
+ """لغو پست زمانبندی شده"""
+ try:
+ result = await scheduler.cancel_scheduled_post(schedule_id)
+ return result
+ except Exception as e:
+ logger.error(f"خطا در لغو پست: {str(e)}")
+ raise HTTPException(status_code=500, detail=str(e))
+
+@app.get("/api/platforms")
+async def get_supported_platforms():
+ """دریافت لیست پلتفرمهای پشتیبانی شده"""
+ return {
+ "platforms": [platform.value for platform in PlatformType],
+ "content_types": [content_type.value for content_type in ContentType]
+ }
+
+@app.get("/api/stats")
+async def get_system_stats():
+ """آمار سیستم"""
+ try:
+ stats = {
+ "total_generated_contents": await content_generator.get_total_generated(),
+ "scheduled_posts_count": await scheduler.get_scheduled_count(),
+ "active_platforms": len(PlatformType),
+ "system_uptime": datetime.now() - app.state.start_time if hasattr(app.state, 'start_time') else None
+ }
+ return stats
+ except Exception as e:
+ logger.error(f"خطا در دریافت آمار: {str(e)}")
+ raise HTTPException(status_code=500, detail=str(e))
+
+@app.on_event("startup")
+async def startup_event():
+ """رویداد راهاندازی اپلیکیشن"""
+ app.state.start_time = datetime.now()
+ logger.info("🚀 سیستم تولید محتوای هوش مصنوعی راهاندازی شد")
+
+ # راهاندازی scheduler
+ await scheduler.start()
+
+@app.on_event("shutdown")
+async def shutdown_event():
+ """رویداد خاموش شدن اپلیکیشن"""
+ logger.info("⛔ سیستم در حال خاموش شدن...")
+ await scheduler.stop()
+
+if __name__ == "__main__":
+ import uvicorn
+ uvicorn.run(
+ "main:app",
+ host="0.0.0.0",
+ port=8000,
+ reload=True,
+ log_level="info"
+ )
\ No newline at end of file
diff --git a/requirements.txt b/requirements.txt
new file mode 100644
index 0000000..5de8ee1
--- /dev/null
+++ b/requirements.txt
@@ -0,0 +1,16 @@
+fastapi==0.104.1
+uvicorn==0.24.0
+pydantic==2.5.0
+python-multipart==0.0.6
+jinja2==3.1.2
+python-jose==3.3.0
+passlib==1.7.4
+bcrypt==4.1.2
+openai==1.3.7
+google-generativeai==0.3.2
+requests==2.31.0
+beautifulsoup4==4.12.2
+python-dateutil==2.8.2
+schedule==1.2.0
+typing-extensions==4.8.0
+aiofiles==23.2.1
\ No newline at end of file
diff --git a/run_demo.py b/run_demo.py
new file mode 100755
index 0000000..20e35e5
--- /dev/null
+++ b/run_demo.py
@@ -0,0 +1,198 @@
+#!/usr/bin/env python3
+"""
+اسکریپت نمایشی برای راهاندازی سریع سیستم تولید محتوای هوش مصنوعی
+"""
+
+import os
+import sys
+import subprocess
+import time
+import webbrowser
+from pathlib import Path
+
+def check_python_version():
+ """بررسی نسخه پایتون"""
+ if sys.version_info < (3, 8):
+ print("❌ نسخه پایتون باید 3.8 یا بالاتر باشد")
+ print(f"نسخه فعلی: {sys.version}")
+ return False
+ print(f"✅ نسخه پایتون: {sys.version.split()[0]}")
+ return True
+
+def install_requirements():
+ """نصب وابستگیها"""
+ print("📦 در حال نصب وابستگیها...")
+ try:
+ subprocess.check_call([
+ sys.executable, "-m", "pip", "install", "-r", "requirements.txt"
+ ])
+ print("✅ وابستگیها با موفقیت نصب شدند")
+ return True
+ except subprocess.CalledProcessError:
+ print("❌ خطا در نصب وابستگیها")
+ return False
+
+def setup_demo_data():
+ """آمادهسازی دادههای نمونه"""
+ print("🔧 آمادهسازی دادههای نمونه...")
+
+ # ایجاد پوشههای مورد نیاز
+ directories = ["logs", "data", "uploads"]
+ for directory in directories:
+ Path(directory).mkdir(exist_ok=True)
+
+ print("✅ دادههای نمونه آماده شدند")
+
+def start_server():
+ """راهاندازی سرور"""
+ print("🚀 راهاندازی سرور...")
+
+ try:
+ # راهاندازی سرور در پسزمینه
+ process = subprocess.Popen([
+ sys.executable, "-m", "uvicorn", "main:app",
+ "--host", "0.0.0.0", "--port", "8000", "--reload"
+ ])
+
+ print("⏳ منتظر راهاندازی سرور...")
+ time.sleep(5) # منتظر راهاندازی سرور
+
+ # بررسی وضعیت سرور
+ if process.poll() is None:
+ print("✅ سرور با موفقیت راهاندازی شد")
+ print("🌐 آدرس سرور: http://localhost:8000")
+ return process
+ else:
+ print("❌ خطا در راهاندازی سرور")
+ return None
+
+ except Exception as e:
+ print(f"❌ خطا در راهاندازی سرور: {e}")
+ return None
+
+def run_demo_examples():
+ """اجرای نمونههای دمو"""
+ print("\n🎯 اجرای نمونههای دمو...")
+
+ try:
+ # منتظر آماده شدن کامل سرور
+ time.sleep(3)
+
+ print("📝 تست تولید محتوا...")
+ subprocess.run([
+ sys.executable, "examples/sample_requests.py"
+ ], timeout=30)
+
+ print("✅ نمونهها با موفقیت اجرا شدند")
+
+ except subprocess.TimeoutExpired:
+ print("⏰ زمان اجرای نمونهها به پایان رسید")
+ except Exception as e:
+ print(f"❌ خطا در اجرای نمونهها: {e}")
+
+def open_browser():
+ """باز کردن مرورگر"""
+ print("🌐 باز کردن مرورگر...")
+ try:
+ webbrowser.open("http://localhost:8000")
+ print("✅ مرورگر باز شد")
+ except Exception as e:
+ print(f"❌ خطا در باز کردن مرورگر: {e}")
+ print("لطفاً خودتان آدرس http://localhost:8000 را در مرورگر باز کنید")
+
+def print_banner():
+ """نمایش بنر خوشامدگویی"""
+ banner = """
+ ╔══════════════════════════════════════════════════════════════════╗
+ ║ ║
+ ║ 🤖 سیستم تولید محتوای هوش مصنوعی چندپلتفرمی ║
+ ║ ║
+ ║ 🚀 نسخه نمایشی 1.0.0 ║
+ ║ ║
+ ╚══════════════════════════════════════════════════════════════════╝
+ """
+ print(banner)
+
+def print_help():
+ """نمایش راهنما"""
+ help_text = """
+ 🎯 ویژگیهای سیستم:
+
+ ✨ تولید محتوا برای 5 پلتفرم (Instagram, Telegram, Website, Eitaa, Rubika)
+ 🔍 بهینهسازی خودکار SEO
+ 🎨 تولید ایدههای بصری
+ ⏰ زمانبندی انتشار هوشمند
+ 📊 آنالیتیک و آمار پیشرفته
+
+ 🌐 آدرسهای مهم:
+ • رابط کاربری: http://localhost:8000
+ • مستندات API: http://localhost:8000/docs
+ • ReDoc: http://localhost:8000/redoc
+
+ ⌨️ کلیدهای میانبر:
+ • Ctrl+Enter: تولید محتوا
+ • Ctrl+S: ذخیره محتوا
+ • Ctrl+C: کپی محتوا
+
+ 🆘 در صورت مشکل:
+ • بررسی کنید Python 3.8+ نصب باشد
+ • از اجرای همزمان چند نمونه خودداری کنید
+ • فایلهای لاگ را در پوشه logs بررسی کنید
+ """
+ print(help_text)
+
+def main():
+ """تابع اصلی"""
+ print_banner()
+
+ # بررسیهای اولیه
+ if not check_python_version():
+ return
+
+ print("🔍 بررسی محیط...")
+
+ # نصب وابستگیها
+ if not install_requirements():
+ print("❌ نصب وابستگیها ناموفق بود")
+ return
+
+ # آمادهسازی
+ setup_demo_data()
+
+ # راهاندازی سرور
+ server_process = start_server()
+ if not server_process:
+ return
+
+ try:
+ print("\n" + "="*70)
+ print("🎉 سیستم آماده است!")
+ print("="*70)
+
+ # نمایش راهنما
+ print_help()
+
+ # باز کردن مرورگر
+ open_browser()
+
+ # اجرای نمونهها (اختیاری)
+ response = input("\n❓ آیا میخواهید نمونههای دمو را اجرا کنید؟ (y/n): ")
+ if response.lower() in ['y', 'yes', 'آری', 'بله']:
+ run_demo_examples()
+
+ print("\n🔄 سرور در حال اجرا است...")
+ print("💡 برای خروج Ctrl+C را فشار دهید")
+
+ # نگه داشتن سرور
+ while True:
+ time.sleep(1)
+
+ except KeyboardInterrupt:
+ print("\n\n🛑 در حال بستن سرور...")
+ server_process.terminate()
+ server_process.wait()
+ print("✅ سرور بسته شد")
+ print("👋 خداحافظ!")
+
+if __name__ == "__main__":
+ main()
\ No newline at end of file
diff --git a/src/__init__.py b/src/__init__.py
new file mode 100644
index 0000000..32d0aa9
--- /dev/null
+++ b/src/__init__.py
@@ -0,0 +1 @@
+# سیستم تولید محتوای هوش مصنوعی چندپلتفرمی
\ No newline at end of file
diff --git a/src/content_generator.py b/src/content_generator.py
new file mode 100644
index 0000000..9afdbd3
--- /dev/null
+++ b/src/content_generator.py
@@ -0,0 +1,452 @@
+"""
+تولیدکننده محتوا برای پلتفرمهای مختلف
+"""
+
+import asyncio
+import json
+import re
+from typing import Dict, List, Optional, Any
+from datetime import datetime
+import logging
+
+from .platforms import (
+ PlatformType, ContentType, ToneType,
+ get_platform_config, get_content_template,
+ PLATFORM_CONFIGS
+)
+from .models import PlatformContent
+
+logger = logging.getLogger(__name__)
+
+class ContentGenerator:
+ """کلاس اصلی تولید محتوا"""
+
+ def __init__(self):
+ self.generated_count = 0
+ self.templates = self._load_templates()
+
+ def _load_templates(self) -> Dict[str, Any]:
+ """بارگذاری قالبهای محتوا"""
+ return {
+ "instagram_hooks": [
+ "آیا میدانستید که...",
+ "راز موفقیت در...",
+ "۵ نکته طلایی برای...",
+ "چرا باید...",
+ "بهترین روش برای...",
+ "اگر میخواهید...",
+ "سوالی که همه میپرسند:",
+ "حقیقتی که کمتر میدانند:",
+ ],
+
+ "cta_templates": {
+ PlatformType.INSTAGRAM: [
+ "نظرتون رو در کامنت بنویسید 👇",
+ "این پست رو ذخیره کنید 💾",
+ "با دوستاتون به اشتراک بگذارید 🔄",
+ "برای محتوای بیشتر فالو کنید 🔔",
+ "در استوری نشانمون بدید 📱"
+ ],
+ PlatformType.TELEGRAM: [
+ "نظرات خود را در گروه مطرح کنید",
+ "این پیام را فوروارد کنید",
+ "به کانال ما بپیوندید",
+ "لینک را با دوستان خود به اشتراک بگذارید",
+ "برای اطلاعات بیشتر کلیک کنید"
+ ],
+ PlatformType.WEBSITE: [
+ "مطالعه بیشتر مقالات مرتبط",
+ "عضویت در خبرنامه",
+ "دانلود راهنمای رایگان",
+ "تماس با کارشناسان ما",
+ "درخواست مشاوره رایگان"
+ ]
+ },
+
+ "hashtag_categories": {
+ "عمومی": ["محتوا", "آموزش", "اطلاعات", "مفید", "جالب"],
+ "تکنولوژی": ["تکنولوژی", "نوآوری", "دیجیتال", "آینده"],
+ "کسب_و_کار": ["کسب_و_کار", "موفقیت", "استارتاپ", "کارآفرینی"],
+ "سبک_زندگی": ["سبک_زندگی", "سلامت", "تناسب_اندام", "آرامش"],
+ "آموزش": ["آموزش", "یادگیری", "مهارت", "توسعه_فردی"]
+ }
+ }
+
+ async def generate_for_platform(
+ self,
+ platform: PlatformType,
+ topic: str,
+ keywords: List[str],
+ tone: ToneType,
+ target_audience: Optional[str] = None,
+ content_type: ContentType = ContentType.POST
+ ) -> PlatformContent:
+ """تولید محتوا برای یک پلتفرم خاص"""
+
+ logger.info(f"تولید محتوا برای {platform.value} - موضوع: {topic}")
+
+ # دریافت تنظیمات پلتفرم
+ config = get_platform_config(platform)
+ template = get_content_template(platform, content_type)
+
+ # تولید محتوای اصلی
+ main_content = await self._generate_main_content(
+ topic=topic,
+ keywords=keywords,
+ tone=tone,
+ platform=platform,
+ content_type=content_type,
+ target_audience=target_audience
+ )
+
+ # اعمال قالب
+ formatted_content = await self._apply_template(
+ content=main_content,
+ template=template,
+ platform=platform,
+ topic=topic
+ )
+
+ # تولید هشتگها
+ hashtags = await self._generate_platform_hashtags(
+ keywords=keywords,
+ platform=platform,
+ topic=topic
+ )
+
+ # محاسبه آمار
+ char_count = len(formatted_content)
+ reading_time = self._estimate_reading_time(formatted_content)
+ engagement_score = await self._calculate_engagement_score(
+ content=formatted_content,
+ platform=platform,
+ hashtags=hashtags
+ )
+
+ # اعمال محدودیتهای پلتفرم
+ if config.get("max_caption_length"):
+ formatted_content = self._truncate_content(
+ formatted_content,
+ config["max_caption_length"]
+ )
+
+ self.generated_count += 1
+
+ return PlatformContent(
+ platform=platform,
+ content=formatted_content,
+ hashtags=hashtags,
+ character_count=char_count,
+ estimated_reading_time=reading_time,
+ engagement_score=engagement_score
+ )
+
+ async def _generate_main_content(
+ self,
+ topic: str,
+ keywords: List[str],
+ tone: ToneType,
+ platform: PlatformType,
+ content_type: ContentType,
+ target_audience: Optional[str] = None
+ ) -> str:
+ """تولید محتوای اصلی"""
+
+ # شخصیسازی بر اساس لحن
+ tone_adjustments = {
+ ToneType.FORMAL: "لطفاً به شیوهای رسمی و حرفهای",
+ ToneType.INFORMAL: "به شکل صمیمی و دوستانه",
+ ToneType.FRIENDLY: "با لحنی گرم و دوستانه",
+ ToneType.PROFESSIONAL: "با رویکرد کاملاً حرفهای",
+ ToneType.HUMOROUS: "با طنز مناسب و شوخطبعی",
+ ToneType.MOTIVATIONAL: "با انگیزهدهی و انرژی مثبت",
+ ToneType.EDUCATIONAL: "به شیوه آموزشی و توضیحی",
+ ToneType.SALES: "با رویکرد فروشی اما نه تهاجمی"
+ }
+
+ # تولید محتوا بر اساس نوع
+ if content_type == ContentType.POST:
+ content = await self._generate_post_content(topic, keywords, tone_adjustments.get(tone, ""))
+ elif content_type == ContentType.STORY:
+ content = await self._generate_story_content(topic, keywords)
+ elif content_type == ContentType.ARTICLE:
+ content = await self._generate_article_content(topic, keywords, tone_adjustments.get(tone, ""))
+ elif content_type == ContentType.NEWS:
+ content = await self._generate_news_content(topic, keywords)
+ elif content_type == ContentType.VIDEO_SCRIPT:
+ content = await self._generate_video_script(topic, keywords)
+ else:
+ content = await self._generate_default_content(topic, keywords, tone_adjustments.get(tone, ""))
+
+ return content
+
+ async def _generate_post_content(self, topic: str, keywords: List[str], tone_instruction: str) -> str:
+ """تولید محتوای پست"""
+
+ # الگوریتم تولید محتوای هوشمند
+ # در اینجا میتوانید از API های مختلف AI استفاده کنید
+
+ content_structure = {
+ "hook": f"موضوع جذاب درباره {topic}",
+ "body": f"محتوای اصلی که کلمات کلیدی {', '.join(keywords)} را شامل میشود",
+ "value": "ارزش و فایده برای مخاطب",
+ "conclusion": "جمعبندی و نتیجهگیری"
+ }
+
+ # ترکیب محتوا
+ content = f"""
+{content_structure['hook']}
+
+{content_structure['body']}
+
+💡 {content_structure['value']}
+
+{content_structure['conclusion']}
+""".strip()
+
+ return content
+
+ async def _generate_story_content(self, topic: str, keywords: List[str]) -> str:
+ """تولید محتوای استوری"""
+ return f"📱 {topic}\n\n{' '.join(keywords[:3])}"
+
+ async def _generate_article_content(self, topic: str, keywords: List[str], tone_instruction: str) -> str:
+ """تولید محتوای مقاله"""
+ return f"""
+# {topic}
+
+## مقدمه
+در این مقاله به بررسی {topic} میپردازیم.
+
+## بخش اصلی
+محتوای مفصل درباره {', '.join(keywords)}.
+
+## نتیجهگیری
+خلاصه و جمعبندی مطالب.
+"""
+
+ async def _generate_news_content(self, topic: str, keywords: List[str]) -> str:
+ """تولید محتوای خبری"""
+ return f"""
+🗞️ خبر: {topic}
+
+📍 خلاصه خبر مربوط به {', '.join(keywords[:3])}
+
+📊 جزئیات و اطلاعات تکمیلی
+
+🔗 منابع معتبر
+"""
+
+ async def _generate_video_script(self, topic: str, keywords: List[str]) -> str:
+ """تولید اسکریپت ویدئو"""
+ return f"""
+🎬 اسکریپت ویدئو: {topic}
+
+[سکانس 1 - معرفی]
+سلام و معرفی موضوع {topic}
+
+[سکانس 2 - محتوای اصلی]
+توضیح درباره {', '.join(keywords)}
+
+[سکانس 3 - خاتمه]
+جمعبندی و تشکر از بینندگان
+"""
+
+ async def _generate_default_content(self, topic: str, keywords: List[str], tone_instruction: str) -> str:
+ """تولید محتوای پیشفرض"""
+ return f"{tone_instruction} درباره {topic} و مرتبط با {', '.join(keywords)} محتوایی تولید کنید."
+
+ async def _apply_template(
+ self,
+ content: str,
+ template: str,
+ platform: PlatformType,
+ topic: str
+ ) -> str:
+ """اعمال قالب به محتوا"""
+
+ # جایگزینی متغیرها در قالب
+ formatted_content = template.format(
+ main_content=content,
+ hook_line=self._get_random_hook(),
+ title=topic,
+ cta_line=self._get_random_cta(platform),
+ hashtags="", # هشتگها جداگانه اضافه میشوند
+ publish_time=datetime.now().strftime("%Y/%m/%d - %H:%M")
+ )
+
+ return formatted_content.strip()
+
+ def _get_random_hook(self) -> str:
+ """انتخاب تصادفی hook"""
+ import random
+ hooks = self.templates["instagram_hooks"]
+ return random.choice(hooks)
+
+ def _get_random_cta(self, platform: PlatformType) -> str:
+ """انتخاب تصادفی CTA"""
+ import random
+ ctas = self.templates["cta_templates"].get(platform, ["عملکرد انجام دهید"])
+ return random.choice(ctas)
+
+ async def _generate_platform_hashtags(
+ self,
+ keywords: List[str],
+ platform: PlatformType,
+ topic: str
+ ) -> List[str]:
+ """تولید هشتگهای مناسب برای پلتفرم"""
+
+ config = get_platform_config(platform)
+ max_hashtags = config.get("max_hashtags", 10)
+
+ hashtags = []
+
+ # هشتگهای مبتنی بر کلمات کلیدی
+ for keyword in keywords:
+ hashtag = self._clean_hashtag(keyword)
+ if hashtag:
+ hashtags.append(f"#{hashtag}")
+
+ # هشتگهای مرتبط با موضوع
+ topic_hashtags = self._generate_topic_hashtags(topic)
+ hashtags.extend(topic_hashtags)
+
+ # هشتگهای عمومی پلتفرم
+ general_hashtags = self._get_general_hashtags(platform)
+ hashtags.extend(general_hashtags[:3])
+
+ # حذف تکراری و محدود کردن تعداد
+ unique_hashtags = list(dict.fromkeys(hashtags))
+
+ if max_hashtags:
+ unique_hashtags = unique_hashtags[:max_hashtags]
+
+ return unique_hashtags
+
+ def _clean_hashtag(self, text: str) -> str:
+ """تمیز کردن متن برای هشتگ"""
+ # حذف کاراکترهای غیرمجاز
+ cleaned = re.sub(r'[^\w\u0600-\u06FF]', '', text)
+ return cleaned if len(cleaned) > 1 else None
+
+ def _generate_topic_hashtags(self, topic: str) -> List[str]:
+ """تولید هشتگهای مرتبط با موضوع"""
+ words = topic.split()
+ hashtags = []
+
+ for word in words:
+ cleaned = self._clean_hashtag(word)
+ if cleaned and len(cleaned) > 2:
+ hashtags.append(f"#{cleaned}")
+
+ return hashtags[:5]
+
+ def _get_general_hashtags(self, platform: PlatformType) -> List[str]:
+ """دریافت هشتگهای عمومی پلتفرم"""
+ general_tags = {
+ PlatformType.INSTAGRAM: ["#اینستاگرام", "#محتوا", "#ایران"],
+ PlatformType.TELEGRAM: ["#تلگرام", "#اطلاعات", "#مفید"],
+ PlatformType.EITAA: ["#ایتا", "#داخلی", "#ایرانی"],
+ PlatformType.RUBIKA: ["#روبیکا", "#پیام_رسان"]
+ }
+ return general_tags.get(platform, [])
+
+ def _estimate_reading_time(self, content: str) -> int:
+ """تخمین زمان مطالعه (ثانیه)"""
+ words_count = len(content.split())
+ # میانگین سرعت خواندن فارسی: ۱۵۰ کلمه در دقیقه
+ reading_time_minutes = words_count / 150
+ return int(reading_time_minutes * 60)
+
+ async def _calculate_engagement_score(
+ self,
+ content: str,
+ platform: PlatformType,
+ hashtags: List[str]
+ ) -> float:
+ """محاسبه امتیاز جذابیت پیشبینی شده"""
+
+ score = 0.0
+
+ # طول مناسب
+ length = len(content)
+ if platform == PlatformType.INSTAGRAM:
+ if 100 <= length <= 500:
+ score += 2.0
+ elif platform == PlatformType.TELEGRAM:
+ if 50 <= length <= 1000:
+ score += 2.0
+
+ # تعداد هشتگ
+ hashtag_count = len(hashtags)
+ if 5 <= hashtag_count <= 15:
+ score += 1.5
+
+ # وجود ایموجی
+ emoji_count = len(re.findall(r'[\U0001F600-\U0001F64F\U0001F300-\U0001F5FF\U0001F680-\U0001F6FF\U0001F1E0-\U0001F1FF]', content))
+ if emoji_count > 0:
+ score += 1.0
+
+ # وجود سوال
+ if '؟' in content:
+ score += 0.5
+
+ # وجود فراخوان عمل
+ cta_keywords = ['کامنت', 'ذخیره', 'اشتراک', 'فالو', 'کلیک']
+ if any(keyword in content for keyword in cta_keywords):
+ score += 1.0
+
+ return min(score, 10.0) # حداکثر ۱۰
+
+ def _truncate_content(self, content: str, max_length: int) -> str:
+ """کوتاه کردن محتوا در صورت تجاوز از حد مجاز"""
+ if len(content) <= max_length:
+ return content
+
+ # کوتاه کردن با حفظ کلمات
+ truncated = content[:max_length-3]
+ last_space = truncated.rfind(' ')
+ if last_space > 0:
+ truncated = truncated[:last_space]
+
+ return truncated + "..."
+
+ async def generate_hashtags(
+ self,
+ topic: str,
+ keywords: List[str],
+ platforms: List[PlatformType]
+ ) -> Dict[str, List[str]]:
+ """تولید هشتگها برای همه پلتفرمها"""
+
+ all_hashtags = {}
+
+ for platform in platforms:
+ hashtags = await self._generate_platform_hashtags(keywords, platform, topic)
+ all_hashtags[platform.value] = hashtags
+
+ return all_hashtags
+
+ async def generate_cta_suggestions(
+ self,
+ topic: str,
+ platforms: List[PlatformType],
+ content_type: ContentType
+ ) -> List[str]:
+ """تولید پیشنهادات فراخوان عمل"""
+
+ suggestions = []
+
+ for platform in platforms:
+ platform_ctas = self.templates["cta_templates"].get(platform, [])
+ suggestions.extend(platform_ctas[:2]) # دو پیشنهاد از هر پلتفرم
+
+ # حذف تکراری
+ unique_suggestions = list(dict.fromkeys(suggestions))
+
+ return unique_suggestions[:10] # حداکثر ۱۰ پیشنهاد
+
+ async def get_total_generated(self) -> int:
+ """دریافت تعداد کل محتواهای تولید شده"""
+ return self.generated_count
\ No newline at end of file
diff --git a/src/models.py b/src/models.py
new file mode 100644
index 0000000..bc9ce5e
--- /dev/null
+++ b/src/models.py
@@ -0,0 +1,178 @@
+"""
+مدلهای دادهای سیستم
+"""
+
+from pydantic import BaseModel, Field, validator
+from typing import List, Optional, Dict, Any, Union
+from datetime import datetime
+from enum import Enum
+
+from .platforms import PlatformType, ContentType, ToneType
+
+class ContentRequest(BaseModel):
+ """درخواست تولید محتوا"""
+ topic: str = Field(..., description="موضوع اصلی محتوا")
+ keywords: List[str] = Field(..., description="کلمات کلیدی")
+ platforms: List[PlatformType] = Field(..., description="پلتفرمهای هدف")
+ content_type: ContentType = Field(default=ContentType.POST, description="نوع محتوا")
+ tone: ToneType = Field(default=ToneType.FRIENDLY, description="لحن محتوا")
+ target_audience: Optional[str] = Field(None, description="مخاطب هدف")
+ language: str = Field(default="fa", description="زبان محتوا")
+ additional_instructions: Optional[str] = Field(None, description="دستورات اضافی")
+
+ @validator('keywords')
+ def validate_keywords(cls, v):
+ if not v or len(v) == 0:
+ raise ValueError("حداقل یک کلمه کلیدی باید وارد شود")
+ return v
+
+ @validator('topic')
+ def validate_topic(cls, v):
+ if not v or len(v.strip()) < 3:
+ raise ValueError("موضوع باید حداقل ۳ کاراکتر باشد")
+ return v.strip()
+
+class PlatformContent(BaseModel):
+ """محتوای تولید شده برای یک پلتفرم"""
+ platform: PlatformType
+ content: str
+ hashtags: List[str] = Field(default_factory=list)
+ mentions: List[str] = Field(default_factory=list)
+ character_count: int = 0
+ estimated_reading_time: Optional[int] = None # بر حسب ثانیه
+ engagement_score: Optional[float] = None # امتیاز جذابیت پیشبینی شده
+
+ class Config:
+ use_enum_values = True
+
+class ContentResponse(BaseModel):
+ """پاسخ تولید محتوا"""
+ contents: Dict[str, PlatformContent]
+ hashtags: Dict[str, List[str]] # هشتگهای پیشنهادی برای هر پلتفرم
+ cta_suggestions: List[str] # پیشنهادات فراخوان عمل
+ generated_at: datetime
+ request_id: str
+ total_platforms: int = 0
+ processing_time: Optional[float] = None # زمان پردازش به ثانیه
+
+ def __init__(self, **data):
+ super().__init__(**data)
+ self.total_platforms = len(self.contents)
+
+class SEOOptimizationRequest(BaseModel):
+ """درخواست بهینهسازی SEO"""
+ text: str = Field(..., description="متن برای بهینهسازی")
+ target_keywords: List[str] = Field(..., description="کلمات کلیدی هدف")
+ focus_keyword: str = Field(..., description="کلمه کلیدی اصلی")
+ meta_description: Optional[str] = Field(None, description="توضیحات متا")
+ title_tag: Optional[str] = Field(None, description="عنوان صفحه")
+
+ @validator('target_keywords')
+ def validate_target_keywords(cls, v):
+ if not v or len(v) == 0:
+ raise ValueError("حداقل یک کلمه کلیدی هدف باید وارد شود")
+ return v
+
+class SEOOptimizationResponse(BaseModel):
+ """پاسخ بهینهسازی SEO"""
+ optimized_content: str
+ seo_title: str
+ meta_description: str
+ keywords_density: Dict[str, float]
+ headings_structure: List[Dict[str, Any]]
+ seo_score: float # امتیاز SEO از ۰ تا ۱۰۰
+ recommendations: List[str]
+ readability_score: float
+ word_count: int
+
+class VisualIdeaRequest(BaseModel):
+ """درخواست تولید ایده بصری"""
+ content: str = Field(..., description="محتوای متنی")
+ platform: PlatformType = Field(..., description="پلتفرم هدف")
+ content_type: ContentType = Field(default=ContentType.POST, description="نوع محتوا")
+ style_preferences: Optional[List[str]] = Field(None, description="ترجیحات سبک")
+ color_scheme: Optional[str] = Field(None, description="طرح رنگی")
+ brand_guidelines: Optional[Dict[str, Any]] = Field(None, description="راهنمای برند")
+
+class VisualIdeaResponse(BaseModel):
+ """پاسخ تولید ایده بصری"""
+ image_ideas: List[Dict[str, Any]]
+ video_ideas: List[Dict[str, Any]]
+ graphic_elements: List[str]
+ color_suggestions: List[str]
+ typography_suggestions: List[str]
+ layout_suggestions: List[str]
+
+class ScheduleRequest(BaseModel):
+ """درخواست زمانبندی انتشار"""
+ platform: PlatformType = Field(..., description="پلتفرم انتشار")
+ content: str = Field(..., description="محتوای قابل انتشار")
+ schedule_time: datetime = Field(..., description="زمان انتشار")
+ auto_publish: bool = Field(default=False, description="انتشار خودکار")
+ repeat_schedule: Optional[str] = Field(None, description="تکرار زمانبندی")
+ tags: List[str] = Field(default_factory=list, description="برچسبها")
+
+ @validator('schedule_time')
+ def validate_schedule_time(cls, v):
+ if v <= datetime.now():
+ raise ValueError("زمان انتشار باید در آینده باشد")
+ return v
+
+class ScheduledPost(BaseModel):
+ """پست زمانبندی شده"""
+ id: str
+ platform: PlatformType
+ content: str
+ schedule_time: datetime
+ status: str = "scheduled" # scheduled, published, failed, cancelled
+ created_at: datetime
+ published_at: Optional[datetime] = None
+ error_message: Optional[str] = None
+ tags: List[str] = Field(default_factory=list)
+
+ class Config:
+ use_enum_values = True
+
+class ContentAnalytics(BaseModel):
+ """آنالیتیک محتوا"""
+ platform: PlatformType
+ content_id: str
+ views: int = 0
+ likes: int = 0
+ comments: int = 0
+ shares: int = 0
+ engagement_rate: float = 0.0
+ reach: int = 0
+ impressions: int = 0
+ click_through_rate: float = 0.0
+ analyzed_at: datetime
+
+ class Config:
+ use_enum_values = True
+
+class UserProfile(BaseModel):
+ """پروفایل کاربر"""
+ user_id: str
+ username: str
+ email: str
+ preferred_platforms: List[PlatformType] = Field(default_factory=list)
+ default_tone: ToneType = ToneType.FRIENDLY
+ brand_voice: Optional[str] = None
+ target_audience: Optional[str] = None
+ industry: Optional[str] = None
+ created_at: datetime
+ last_active: datetime
+ subscription_type: str = "free" # free, premium, enterprise
+
+ class Config:
+ use_enum_values = True
+
+class SystemStats(BaseModel):
+ """آمار سیستم"""
+ total_content_generated: int
+ total_users: int
+ popular_platforms: Dict[str, int]
+ popular_content_types: Dict[str, int]
+ average_engagement_score: float
+ uptime_percentage: float
+ last_updated: datetime
\ No newline at end of file
diff --git a/src/platforms.py b/src/platforms.py
new file mode 100644
index 0000000..8e5fa6c
--- /dev/null
+++ b/src/platforms.py
@@ -0,0 +1,237 @@
+"""
+تعریف پلتفرمها و انواع محتوا
+"""
+
+from enum import Enum
+from typing import Dict, List
+
+class PlatformType(Enum):
+ """انواع پلتفرمهای پشتیبانی شده"""
+ INSTAGRAM = "instagram"
+ TELEGRAM = "telegram"
+ WEBSITE = "website"
+ EITAA = "eitaa"
+ RUBIKA = "rubika"
+
+class ContentType(Enum):
+ """انواع محتوا"""
+ POST = "post"
+ STORY = "story"
+ ARTICLE = "article"
+ NEWS = "news"
+ ADVERTISEMENT = "advertisement"
+ VIDEO_SCRIPT = "video_script"
+ CAROUSEL = "carousel"
+ REEL_SCRIPT = "reel_script"
+
+class ToneType(Enum):
+ """انواع لحن"""
+ FORMAL = "formal"
+ INFORMAL = "informal"
+ FRIENDLY = "friendly"
+ PROFESSIONAL = "professional"
+ HUMOROUS = "humorous"
+ MOTIVATIONAL = "motivational"
+ EDUCATIONAL = "educational"
+ SALES = "sales"
+
+# تنظیمات و محدودیتهای هر پلتفرم
+PLATFORM_CONFIGS = {
+ PlatformType.INSTAGRAM: {
+ "max_caption_length": 2200,
+ "max_hashtags": 30,
+ "supports_emojis": True,
+ "supports_mentions": True,
+ "line_breaks": True,
+ "preferred_content_types": [
+ ContentType.POST,
+ ContentType.STORY,
+ ContentType.CAROUSEL,
+ ContentType.REEL_SCRIPT
+ ],
+ "hashtag_prefix": "#",
+ "mention_prefix": "@",
+ "best_posting_times": ["9:00", "12:00", "17:00", "20:00"],
+ "character_encoding": "utf-8"
+ },
+
+ PlatformType.TELEGRAM: {
+ "max_caption_length": 4096,
+ "max_hashtags": None, # بدون محدودیت
+ "supports_emojis": True,
+ "supports_mentions": True,
+ "supports_markdown": True,
+ "supports_html": True,
+ "line_breaks": True,
+ "preferred_content_types": [
+ ContentType.POST,
+ ContentType.NEWS,
+ ContentType.ARTICLE
+ ],
+ "hashtag_prefix": "#",
+ "mention_prefix": "@",
+ "best_posting_times": ["8:00", "13:00", "18:00", "21:00"],
+ "character_encoding": "utf-8"
+ },
+
+ PlatformType.WEBSITE: {
+ "max_caption_length": None, # بدون محدودیت
+ "supports_html": True,
+ "supports_seo": True,
+ "requires_headings": True,
+ "requires_meta_tags": True,
+ "preferred_content_types": [
+ ContentType.ARTICLE,
+ ContentType.NEWS
+ ],
+ "seo_requirements": {
+ "title_max_length": 60,
+ "meta_description_max_length": 160,
+ "h1_required": True,
+ "alt_text_required": True
+ },
+ "character_encoding": "utf-8"
+ },
+
+ PlatformType.EITAA: {
+ "max_caption_length": 4096,
+ "max_hashtags": 20,
+ "supports_emojis": True,
+ "supports_mentions": True,
+ "line_breaks": True,
+ "preferred_content_types": [
+ ContentType.POST,
+ ContentType.NEWS
+ ],
+ "hashtag_prefix": "#",
+ "mention_prefix": "@",
+ "best_posting_times": ["10:00", "14:00", "19:00", "22:00"],
+ "character_encoding": "utf-8"
+ },
+
+ PlatformType.RUBIKA: {
+ "max_caption_length": 4096,
+ "max_hashtags": 15,
+ "supports_emojis": True,
+ "supports_mentions": True,
+ "line_breaks": True,
+ "preferred_content_types": [
+ ContentType.POST,
+ ContentType.NEWS
+ ],
+ "hashtag_prefix": "#",
+ "mention_prefix": "@",
+ "best_posting_times": ["11:00", "15:00", "20:00", "23:00"],
+ "character_encoding": "utf-8"
+ }
+}
+
+# قالبهای محتوا برای هر پلتفرم
+CONTENT_TEMPLATES = {
+ PlatformType.INSTAGRAM: {
+ ContentType.POST: """
+{hook_line}
+
+{main_content}
+
+{cta_line}
+
+{hashtags}
+""",
+ ContentType.STORY: """
+{main_content}
+
+{cta_text}
+""",
+ ContentType.CAROUSEL: """
+اسلاید {slide_number}: {title}
+
+{content}
+
+{navigation_hint}
+""",
+ ContentType.REEL_SCRIPT: """
+🎬 سکانس {scene_number}
+⏱️ مدت: {duration} ثانیه
+
+{scene_description}
+
+متن روی صفحه: {overlay_text}
+موزیک: {music_suggestion}
+"""
+ },
+
+ PlatformType.TELEGRAM: {
+ ContentType.POST: """
+
+
+
هیچ محتوای زمانبندی شدهای وجود ندارد
+
+ `;
+ return;
+ }
+
+ posts.forEach(post => {
+ const postElement = document.createElement('div');
+ postElement.className = 'scheduled-item';
+
+ const scheduleDate = new Date(post.schedule_time);
+ const isOverdue = scheduleDate < new Date() && post.status === 'scheduled';
+
+ postElement.innerHTML = `
+
+
+
+
+ ${this.getPlatformName(post.platform)}
+ ${this.getStatusText(post.status)}
+ ${isOverdue ? 'عقبافتاده ' : ''}
+
+
+
+ ${this.formatDate(scheduleDate)}
+
+
+
+ ${post.status === 'scheduled' ? `
+
+
+
+
+
+
+ ` : ''}
+
+
+
+ ${post.content.substring(0, 100)}${post.content.length > 100 ? '...' : ''}
+
+ `;
+
+ container.appendChild(postElement);
+ });
+ }
+
+ getStatusText(status) {
+ const texts = {
+ 'scheduled': 'زمانبندی شده',
+ 'published': 'منتشر شده',
+ 'failed': 'ناموفق',
+ 'cancelled': 'لغو شده'
+ };
+ return texts[status] || status;
+ }
+
+ formatDate(date) {
+ return new Intl.DateTimeFormat('fa-IR', {
+ year: 'numeric',
+ month: 'long',
+ day: 'numeric',
+ hour: '2-digit',
+ minute: '2-digit'
+ }).format(date);
+ }
+
+ async cancelScheduledPost(id) {
+ if (!confirm('آیا از لغو این پست اطمینان دارید؟')) return;
+
+ try {
+ const response = await fetch(`${this.apiBase}/scheduled-posts/${id}`, {
+ method: 'DELETE'
+ });
+
+ if (!response.ok) {
+ throw new Error(`خطای سرور: ${response.status}`);
+ }
+
+ this.showToast('پست با موفقیت لغو شد', 'success');
+ this.loadScheduledPosts();
+
+ } catch (error) {
+ console.error('خطا در لغو پست:', error);
+ this.showToast(`خطا در لغو پست: ${error.message}`, 'error');
+ }
+ }
+
+ async loadStats() {
+ try {
+ const response = await fetch(`${this.apiBase}/stats`);
+ if (!response.ok) return;
+
+ const stats = await response.json();
+ this.displayStats(stats);
+
+ } catch (error) {
+ console.error('خطا در بارگذاری آمار:', error);
+ }
+ }
+
+ displayStats(stats) {
+ document.getElementById('totalGenerated').textContent = stats.total_generated_contents || 0;
+ document.getElementById('totalScheduled').textContent = stats.scheduled_posts_count || 0;
+ document.getElementById('totalPublished').textContent = '0'; // از API دریافت شود
+ document.getElementById('totalViews').textContent = '0'; // از API دریافت شود
+ }
+
+ setupCharts() {
+ // نمودار عملکرد
+ const performanceCtx = document.getElementById('performanceChart').getContext('2d');
+ this.charts.performance = new Chart(performanceCtx, {
+ type: 'line',
+ data: {
+ labels: ['شنبه', 'یکشنبه', 'دوشنبه', 'سهشنبه', 'چهارشنبه', 'پنجشنبه', 'جمعه'],
+ datasets: [{
+ label: 'محتوای تولید شده',
+ data: [12, 19, 8, 15, 22, 18, 25],
+ borderColor: '#6366f1',
+ backgroundColor: 'rgba(99, 102, 241, 0.1)',
+ tension: 0.4
+ }]
+ },
+ options: {
+ responsive: true,
+ maintainAspectRatio: false,
+ plugins: {
+ legend: {
+ labels: {
+ font: {
+ family: 'Vazir'
+ }
+ }
+ }
+ },
+ scales: {
+ y: {
+ beginAtZero: true,
+ ticks: {
+ font: {
+ family: 'Vazir'
+ }
+ }
+ },
+ x: {
+ ticks: {
+ font: {
+ family: 'Vazir'
+ }
+ }
+ }
+ }
+ }
+ });
+
+ // نمودار پلتفرمها
+ const platformCtx = document.getElementById('platformChart').getContext('2d');
+ this.charts.platform = new Chart(platformCtx, {
+ type: 'doughnut',
+ data: {
+ labels: ['اینستاگرام', 'تلگرام', 'وبسایت', 'ایتا', 'روبیکا'],
+ datasets: [{
+ data: [30, 25, 20, 15, 10],
+ backgroundColor: [
+ '#e1306c',
+ '#0088cc',
+ '#10b981',
+ '#06b6d4',
+ '#f59e0b'
+ ]
+ }]
+ },
+ options: {
+ responsive: true,
+ maintainAspectRatio: false,
+ plugins: {
+ legend: {
+ position: 'bottom',
+ labels: {
+ font: {
+ family: 'Vazir'
+ }
+ }
+ }
+ }
+ }
+ });
+ }
+
+ async refreshStats() {
+ await this.loadStats();
+
+ // بروزرسانی نمودارها با دادههای جدید
+ // این بخش را بر اساس API واقعی تکمیل کنید
+ }
+
+ copyContent(platform) {
+ const contentElement = document.getElementById(`content-${platform}`);
+ this.copyText(contentElement.textContent);
+ }
+
+ copyAllContent() {
+ if (!this.currentContent) return;
+
+ let allContent = '';
+ Object.entries(this.currentContent.contents).forEach(([platform, content]) => {
+ allContent += `=== ${this.getPlatformName(platform)} ===\n`;
+ allContent += (content.content || content) + '\n\n';
+ });
+
+ this.copyText(allContent);
+ }
+
+ copyText(text) {
+ navigator.clipboard.writeText(text).then(() => {
+ this.showToast('متن کپی شد!', 'success');
+ }).catch(err => {
+ console.error('خطا در کپی:', err);
+ this.showToast('خطا در کپی متن', 'error');
+ });
+ }
+
+ saveContent() {
+ if (!this.currentContent) return;
+
+ const data = JSON.stringify(this.currentContent, null, 2);
+ const blob = new Blob([data], { type: 'application/json' });
+ const url = URL.createObjectURL(blob);
+
+ const a = document.createElement('a');
+ a.href = url;
+ a.download = `content-${Date.now()}.json`;
+ document.body.appendChild(a);
+ a.click();
+ document.body.removeChild(a);
+ URL.revokeObjectURL(url);
+
+ this.showToast('محتوا ذخیره شد!', 'success');
+ }
+
+ async optimizeSEO() {
+ if (!this.currentContent) {
+ this.showToast('ابتدا محتوایی تولید کنید', 'error');
+ return;
+ }
+
+ // نمایش مودال SEO
+ const modal = new bootstrap.Modal(document.getElementById('seoModal'));
+ modal.show();
+
+ // شبیهسازی بهینهسازی SEO
+ document.getElementById('seoResults').innerHTML = `
+
+
+ در حال بهینهسازی...
+
+
در حال تحلیل و بهینهسازی محتوا...
+
+ `;
+
+ // شبیهسازی تاخیر
+ setTimeout(() => {
+ document.getElementById('seoResults').innerHTML = `
+
+
+ در حال تولید ایدهها...
+
+
در حال تولید ایدههای بصری خلاقانه...
+
+ `;
+
+ // شبیهسازی تولید ایدهها
+ setTimeout(() => {
+ document.getElementById('visualResults').innerHTML = `
+