Commit ·
2706084
0
Parent(s):
Initial backend commit
Browse filesFiles changed (11)
- .env.exampleAdded+3
- .gitignoreAdded+9
- DockerfileAdded+22
- README.mdAdded+37
- app/db/database.pyAdded+19
- app/main.pyAdded+357
- app/models/models.pyAdded+36
- app/schemas/schemas.pyAdded+67
- app/services/scraper.pyAdded+117
- requirements.txtAdded+12
- scripts/seed.pyAdded+73
123GROQ_API_KEY=your_groq_api_key_hereCORS_ORIGINS=https://YOUR_PROJECT.vercel.app,http://localhost:5173DATABASE_URL=sqlite:///./smart_reader.db123456789.env__pycache__/*.pyc*.pyo*.pyd*.db*.sqlite.pytest_cache/error.log12345678910111213141516171819202122FROM python:3.11-slim
# Set working directoryWORKDIR /app
# Install uvCOPY --from=ghcr.io/astral-sh/uv:latest /uv /uvx /bin/
# Copy requirements first to leverage Docker cacheCOPY requirements.txt .
# Install dependencies using uvRUN uv pip install --system --no-cache -r requirements.txt
# Copy the rest of the application codeCOPY . .
# Expose port 7860 for HuggingFace SpacesEXPOSE 7860
# Run Uvicorn on 0.0.0.0:7860CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "7860"]12345678910111213141516171819202122232425262728293031323334353637# Smart Reader Backend
This is the FastAPI backend for the Smart Reader application, designed to be deployed on HuggingFace Spaces.
## Requirements- Python 3.11+- Groq API Key
## Environment VariablesCreate a `.env` file in the root directory and add the following variables:```GROQ_API_KEY=your_groq_api_key_hereCORS_ORIGINS=https://YOUR_PROJECT.vercel.app,http://localhost:5173DATABASE_URL=sqlite:///./smart_reader.db```
## Local Development1. Install dependencies: ```bash pip install -r requirements.txt ```2. Run the application: ```bash uvicorn main:app --reload --port 8080 ```
## DockerBuild and run the Docker container locally:```bashdocker build -t smart-reader-backend .docker run -p 7860:7860 --env-file .env smart-reader-backend```
## HuggingFace DeploymentThis repository is configured for HuggingFace Spaces using Docker.- The `Dockerfile` exposes port `7860`.- Set your `GROQ_API_KEY` and `CORS_ORIGINS` in the HuggingFace Spaces secrets configuration.12345678910111213141516171819from sqlalchemy import create_enginefrom sqlalchemy.ext.declarative import declarative_basefrom sqlalchemy.orm import sessionmaker
SQLALCHEMY_DATABASE_URL = "sqlite:///./smart_reader.db"
engine = create_engine( SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False})SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
def get_db(): db = SessionLocal() try: yield db finally: db.close()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357import osimport sysfrom fastapi import FastAPI, Depends, HTTPException, UploadFile, Filefrom fastapi.middleware.cors import CORSMiddlewarefrom sqlalchemy.orm import Sessionfrom typing import Listfrom dotenv import load_dotenv
# Force UTF-8 encoding for standard output to prevent Uvicorn from crashing when logging Arabic URLs on Windowsif sys.platform == 'win32' and sys.stdout: sys.stdout.reconfigure(encoding='utf-8')
from app.db.database import engine, get_dbfrom app.models import modelsfrom app.schemas import schemasfrom app.services.scraper import scrape_article_url
# Load environment variables from .env fileload_dotenv()
# Initialize database tablesmodels.Base.metadata.create_all(bind=engine)
app = FastAPI(title="Smart Reader API", version="1.0.0")
# --- CORS Middleware Configuration ---cors_origins_str = os.environ.get("CORS_ORIGINS", "")if cors_origins_str: allow_origins = [origin.strip() for origin in cors_origins_str.split(",")]else: allow_origins = ["*"] # Fallback for local development if not set
app.add_middleware( CORSMiddleware, allow_origins=allow_origins, allow_credentials=True, allow_methods=["*"], allow_headers=["*"],)
# --- Sentiment Analysis Helper ---def analyze_sentiment(text: str) -> str: """ Analyzes the sentiment of a comment text. Works for both Arabic and English using a keyword-based lexicon approach. """ t = text.lower() positive_keywords = [ "جميل", "رائع", "ممتاز", "مفيد", "شكرا", "تحفة", "حب", "جيد", "حلو", "عظيم", "أعجبني", "قوي", "سهل", "واضح", "nice", "good", "great", "awesome", "love", "useful", "thanks", "like", "easy" ] negative_keywords = [ "سيء", "صعب", "ملل", "خطأ", "فشل", "ضعيف", "لا يعجبني", "حزين", "أسف", "وحش", "ركيك", "ممل", "معقد", "ناقص", "bad", "worst", "boring", "error", "fail", "sad", "dislike", "hate", "hard", "difficult" ] pos_count = sum(1 for word in positive_keywords if word in t) neg_count = sum(1 for word in negative_keywords if word in t) if pos_count > neg_count: return "POSITIVE" elif neg_count > pos_count: return "NEGATIVE" return "NEUTRAL"
# --- AI Summarization Helper ---def generate_ai_summary(content: str) -> str: """ Generates a summary of the article using Groq API. Falls back to a clean local extraction summary if no Groq API Key is set. """ api_key = os.environ.get("GROQ_API_KEY") if api_key and api_key.strip(): try: from groq import Groq client = Groq(api_key=api_key) response = client.chat.completions.create( model="llama-3.3-70b-versatile", messages=[ {"role": "system", "content": "You are a professional summarizer. You MUST output ONLY the raw summary text. No intro, no outro, no conversational filler. Summarize the text in the exact same language as the input text."}, {"role": "user", "content": f"Summarize this text in 2-3 sentences. Start immediately with the first word of the summary:\n\n{content[:4000]}"} ], max_tokens=300, ) summary = response.choices[0].message.content.strip() # Programmatically strip common conversational fillers fillers = [ "Here is a summary of the text", "Here is a summary", "Here is the summary", "Sure, here is a summary", "The text can be summarized as follows:", "This text is about", "إليك ملخص", "فيما يلي ملخص" ] for filler in fillers: if summary.lower().startswith(filler.lower()): # Find the end of the first line or colon and slice it idx = summary.find("\n\n") if idx != -1: summary = summary[idx+2:].strip() else: idx = summary.find(":") if idx != -1 and idx < 100: summary = summary[idx+1:].strip() return summary.strip('"\'- \n') except Exception as e: print(f"Error calling Groq API: {e}") # Fallback / Local summarization (First 2 full sentences) sentences = content.replace("\n", " ").split(".") fallback_summary = ". ".join([s.strip() for s in sentences[:2] if s.strip()]) if fallback_summary: return fallback_summary + "." return content[:150] + "..."
# --- Endpoints ---
@app.get("/api/v1/articles", response_model=List[schemas.ArticleResponse])def get_articles(db: Session = Depends(get_db)): articles = db.query(models.Article).all() return articles
@app.get("/api/v1/ai/articles/{article_id}/summary")def get_article_summary(article_id: int, db: Session = Depends(get_db)): article = db.query(models.Article).filter(models.Article.id == article_id).first() if not article: raise HTTPException(status_code=404, detail="المقال غير موجود") # Generate live summary summary = generate_ai_summary(article.content) return summary
@app.post("/api/v1/comments", response_model=schemas.CommentResponse)def create_comment(comment_in: schemas.CommentCreate, db: Session = Depends(get_db)): user_id = comment_in.user.id if comment_in.user else 1 user = db.query(models.User).filter(models.User.id == user_id).first() if not user: user = models.User(id=user_id, name="مستخدم جديد") db.add(user) db.commit() db.refresh(user)
article_id = None if comment_in.article and hasattr(comment_in.article, 'id'): article_id = comment_in.article.id if not article_id: raise HTTPException(status_code=400, detail="يجب تحديد المقال المرتبط بالتعليق")
article = db.query(models.Article).filter(models.Article.id == article_id).first() if not article: raise HTTPException(status_code=404, detail="المقال غير موجود")
sentiment = analyze_sentiment(comment_in.text)
db_comment = models.Comment( text=comment_in.text, sentiment=sentiment, user_id=user.id, article_id=article.id ) db.add(db_comment) db.commit() db.refresh(db_comment) return db_comment
# --- 🚀 Upgraded Scraping Endpoint ---@app.post("/api/v1/articles/scrape", response_model=schemas.ArticleResponse)def scrape_and_add_article(req: schemas.ScrapeRequest, db: Session = Depends(get_db)): scraped_data = scrape_article_url(req.url) # Auto-generate next ID max_id_article = db.query(models.Article).order_by(models.Article.id.desc()).first() next_id = (max_id_article.id + 1) if max_id_article else 1 db_article = models.Article( id=next_id, title=scraped_data["title"], content=scraped_data["content"], category=scraped_data["category"], author=scraped_data["author"], image=scraped_data["image"], summary="" # Generate on demand ) db.add(db_article) db.commit() db.refresh(db_article) return db_article
# --- 📁 File Upload Endpoint ---import ioimport docxfrom PyPDF2 import PdfReader
@app.post("/api/v1/articles/upload", response_model=schemas.ArticleResponse)async def upload_document(file: UploadFile = File(...), db: Session = Depends(get_db)): if not file.filename: raise HTTPException(status_code=400, detail="الملف غير صالح") ext = file.filename.split('.')[-1].lower() content_text = "" title = file.filename.rsplit('.', 1)[0] try: file_bytes = await file.read() if ext == "txt": content_text = file_bytes.decode('utf-8', errors='ignore') elif ext == "pdf": reader = PdfReader(io.BytesIO(file_bytes)) for page in reader.pages: text = page.extract_text() if text: content_text += text + "\n" elif ext == "docx": doc = docx.Document(io.BytesIO(file_bytes)) for para in doc.paragraphs: content_text += para.text + "\n" else: raise HTTPException(status_code=400, detail="نوع الملف غير مدعوم. يرجى رفع ملفات (pdf, docx, txt)") if not content_text.strip(): raise HTTPException(status_code=400, detail="لم نتمكن من قراءة أي نص من الملف") # Add to database as article max_id_article = db.query(models.Article).order_by(models.Article.id.desc()).first() next_id = (max_id_article.id + 1) if max_id_article else 1 db_article = models.Article( id=next_id, title=title, content=content_text.strip(), category="مستند مرفوع", author="أنت", image=None, summary="" ) db.add(db_article) db.commit() db.refresh(db_article) return db_article except HTTPException: raise except Exception as e: raise HTTPException(status_code=500, detail=f"حدث خطأ أثناء معالجة الملف: {str(e)}")
# --- 🚀 Upgraded Chatbot (RAG) Endpoint ---@app.post("/api/v1/ai/articles/{article_id}/chat")def chat_with_article(article_id: int, chat_req: schemas.ChatRequest, db: Session = Depends(get_db)): article = db.query(models.Article).filter(models.Article.id == article_id).first() if not article: raise HTTPException(status_code=404, detail="المقال غير موجود") api_key = os.environ.get("GROQ_API_KEY") if not api_key or not api_key.strip(): # Fallback offline replies user_msg = chat_req.message.lower() if any(greeting in user_msg for greeting in ["مرحباً", "hello", "hi", "سلام", "هلا"]): return {"reply": "أهلاً بك! أنا مساعدك الذكي لقراءة وتلخيص هذا المقال. كيف يمكنني مساعدتك اليوم؟"} if any(kw in user_msg for kw in ["لخص", "ملخص", "summary", "summarize"]): summary_text = article.summary if article.summary else generate_ai_summary(article.content) return {"reply": f"إليك ملخص سريع للمقال:\n{summary_text}"} return {"reply": f"أهلاً بك! لم يتم ضبط مفتاح Groq API Key في ملف `.env` بعد. يمكنك الحصول عليه مجاناً من https://console.groq.com"} try: from groq import Groq client = Groq(api_key=api_key) system_prompt = f"""أنت مساعد قراءة ذكي وتفاعلي لموقع "Smart Reader". وظيفتك الإجابة عن أي أسئلة يطرحها القارئ حول المقال التالي بدقة بالغة وبنفس لغة سؤال القارئ (العربية أو الإنجليزية).تجنب تأليف معلومات ليست في المقال، وإذا سألك عن موضوع عام غير موجود بالمقال وضح له ذلك ثم أجب باختصار وبشكل مفيد.
محتوى المقال كمرجع لك:العنوان: {article.title}الكاتب: {article.author}التصنيف: {article.category}المحتوى:{article.content[:4000]}""" # Build messages from history messages = [{"role": "system", "content": system_prompt}] if chat_req.history: for h in chat_req.history: role = "user" if h.role == "user" else "assistant" messages.append({"role": role, "content": h.content}) messages.append({"role": "user", "content": chat_req.message}) response = client.chat.completions.create( model="llama-3.3-70b-versatile", messages=messages, max_tokens=1024, ) return {"reply": response.choices[0].message.content.strip()} except Exception as e: print(f"Groq Chat error: {e}") return {"reply": f"حدث خطأ أثناء الاتصال بالذكاء الاصطناعي: {str(e)}"}
# --- 🔍 Web Search Endpoint ---@app.get("/api/v1/search", response_model=List[schemas.SearchResult])def web_search(q: str, max_results: int = 8): """ Searches Wikipedia (Arabic or English depending on query) and returns article results. """ if not q or not q.strip(): raise HTTPException(status_code=400, detail="يجب إدخال كلمة بحث") try: import urllib.request import urllib.parse import json import re
# Detect if query has Arabic characters is_arabic = bool(re.search(r'[\u0600-\u06FF]', q)) lang = "ar" if is_arabic else "en" # Wikipedia Search API url = f"https://{lang}.wikipedia.org/w/api.php?action=query&list=search&srsearch={urllib.parse.quote(q)}&utf8=&format=json&srlimit={max_results}" req = urllib.request.Request(url, headers={'User-Agent': 'SmartReader/1.0'}) with urllib.request.urlopen(req, timeout=10) as response: data = json.loads(response.read().decode('utf-8')) results = [] for item in data.get('query', {}).get('search', []): title = item.get('title', '') # Clean HTML tags from snippet snippet_html = item.get('snippet', '') snippet = re.sub(r'<[^>]+>', '', snippet_html) # Construct Wikipedia URL article_url = f"https://{lang}.wikipedia.org/wiki/{urllib.parse.quote(title.replace(' ', '_'))}" results.append(schemas.SearchResult( title=title, url=article_url, snippet=snippet, image=None, source="ويكيبيديا" if is_arabic else "Wikipedia" )) return results except Exception as e: import traceback with open("error.log", "w", encoding="utf-8") as f: f.write(traceback.format_exc()) raise HTTPException(status_code=500, detail=f"حدث خطأ أثناء البحث: {str(e)}")123456789101112131415161718192021222324252627282930313233343536from sqlalchemy import Column, Integer, String, Text, ForeignKeyfrom sqlalchemy.orm import relationshipfrom app.db.database import Base
class User(Base): __tablename__ = "users"
id = Column(Integer, primary_key=True, index=True) name = Column(String(100), nullable=False)
comments = relationship("Comment", back_populates="user")
class Article(Base): __tablename__ = "articles"
id = Column(Integer, primary_key=True, index=True) title = Column(String(255), nullable=False) content = Column(Text, nullable=False) category = Column(String(100)) author = Column(String(100)) image = Column(String(500)) summary = Column(Text, nullable=True)
comments = relationship("Comment", back_populates="article", cascade="all, delete-orphan")
class Comment(Base): __tablename__ = "comments"
id = Column(Integer, primary_key=True, index=True) text = Column(Text, nullable=False) sentiment = Column(String(20), default="NEUTRAL") # POSITIVE, NEGATIVE, NEUTRAL user_id = Column(Integer, ForeignKey("users.id")) article_id = Column(Integer, ForeignKey("articles.id"))
user = relationship("User", back_populates="comments") article = relationship("Article", back_populates="comments")12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667from pydantic import BaseModelfrom typing import List, Optional
# --- User Schemas ---class UserBase(BaseModel): id: int name: str
class Config: from_attributes = True
# --- Comment Schemas ---class CommentCreate(BaseModel): text: str user: Optional[UserBase] = None article: Optional[BaseModel] = None # We will handle nested article ID parsing in main
class Config: from_attributes = True
class CommentResponse(BaseModel): id: int text: str sentiment: str user: Optional[UserBase] = None
class Config: from_attributes = True
# --- Article Schemas ---class ArticleBase(BaseModel): id: int title: str content: str category: Optional[str] = None author: Optional[str] = None image: Optional[str] = None summary: Optional[str] = None
class Config: from_attributes = True
class ArticleResponse(ArticleBase): comments: List[CommentResponse] = []
class Config: from_attributes = True
# --- Chat & Scraping Upgrades ---class ScrapeRequest(BaseModel): url: str
class ChatMessage(BaseModel): role: str # "user" or "model" content: str
class ChatRequest(BaseModel): message: str history: Optional[List[ChatMessage]] = None
# --- Web Search Schema ---class SearchResult(BaseModel): title: str url: str snippet: Optional[str] = None image: Optional[str] = None source: Optional[str] = None123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117import requestsfrom bs4 import BeautifulSoupimport refrom urllib.parse import urljoin, urlparse
def scrape_article_url(url: str) -> dict: """ Scrapes a webpage URL and extracts: - title - content (main body text) - author - image (cover image) - category """ 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" } try: response = requests.get(url, headers=headers, timeout=10) response.raise_for_status() # Detect encoding if response.encoding == 'ISO-8859-1': response.encoding = response.apparent_encoding soup = BeautifulSoup(response.text, "html.parser") # 1. Extract Title title = "" # Try og:title first og_title = soup.find("meta", property="og:title") if og_title and og_title.get("content"): title = og_title["content"] else: # Try <h1> h1 = soup.find("h1") if h1: title = h1.get_text().strip() else: title_tag = soup.find("title") if title_tag: title = title_tag.get_text().strip() if not title: title = "مقال مستخلص من الويب" # 2. Extract Author author = "كاتب ويب" author_meta = soup.find("meta", attrs={"name": "author"}) or soup.find("meta", property="article:author") if author_meta and author_meta.get("content"): author = author_meta["content"].strip() else: # Search for typical author classes author_tag = soup.find(class_=re.compile(r"author|byline|writer", re.I)) if author_tag: author = author_tag.get_text().strip() # 3. Extract Cover Image image_url = "https://images.unsplash.com/photo-1451187580459-43490279c0fa?w=600&auto=format&fit=crop&q=60" # default og_image = soup.find("meta", property="og:image") if og_image and og_image.get("content"): image_url = og_image["content"] else: # Try finding the first large image in body for img in soup.find_all("img"): src = img.get("src") if src and not src.endswith(".gif") and not src.endswith(".svg"): # Resolve relative url image_url = urljoin(url, src) break
# 4. Extract Main Content # Remove noisy elements for element in soup(["script", "style", "nav", "footer", "header", "aside", "form"]): element.extract() # Find paragraphs paragraphs = soup.find_all("p") text_blocks = [] for p in paragraphs: text = p.get_text().strip() # Ignore short/noise paragraphs (less than 30 characters) if len(text) > 30: text_blocks.append(text) content = "\n\n".join(text_blocks) if not content: # Fallback: get raw body text if no paragraphs are found content = soup.body.get_text(separator="\n\n").strip() if soup.body else "تعذر استخلاص محتوى النص من هذا الموقع." # Limit length if it's too raw and full of noise content = content[:3000]
# 5. Extract/Guess Category or Domain Name domain = urlparse(url).netloc.replace("www.", "") category = domain.split(".")[0].capitalize() return { "title": title, "content": content, "author": author, "image": image_url, "category": category } except Exception as e: import traceback traceback.print_exc() print(f"Scraping error: {e}") return { "title": "فشل جلب المقال", "content": f"حدث خطأ أثناء محاولة الاتصال بالموقع أو جلب محتواه:\n{str(e)}", "author": "خطأ النظام", "image": "https://images.unsplash.com/photo-1594322436404-5a0526db4d13?w=600&auto=format&fit=crop&q=60", "category": "خطأ" }123456789101112fastapi==0.115.8uvicorn==0.34.0sqlalchemy==2.0.38pydantic==2.10.6google-generativeai==0.8.4beautifulsoup4==4.12.3python-dotenv==1.0.1requests==2.32.3groq==0.13.1python-multipart==0.0.20PyPDF2==3.0.1python-docx==1.1.212345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273import sysimport os
# Add parent directory to path so database modules can be importedsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from app.db.database import engine, SessionLocal, Basefrom app.models import models
def seed_db(): # Recreate tables Base.metadata.drop_all(bind=engine) Base.metadata.create_all(bind=engine)
db = SessionLocal() try: # Create a test user with ID 1 (required by the frontend comment payload) test_user = models.User(id=1, name="أحمد علي") db.add(test_user) db.commit()
# Add sample articles articles = [ models.Article( id=1, title="مستقبل الذكاء الاصطناعي في الطب", content="""شهد قطاع الطب ثورة هائلة بفضل تقنيات الذكاء الاصطناعي في الآونة الأخيرة. تُستخدم خوارزميات التعلم العميق الآن في تشخيص الأمراض المعقدة مثل السرطان بدقة تتفوق أحياناً على أمهر الأطباء. علاوة على ذلك، يساهم الذكاء الاصطناعي في تسريع عملية تطوير الأدوية الجديدة من خلال التنبؤ بكيفية تفاعل الجزيئات الكيميائية، مما يوفر سنوات من البحث السريري والملايين من الدولارات. في المستقبل القريب، سنرى روبوتات جراحية تعمل بدعم كامل من الذكاء الاصطناعي لتقليل الأخطاء البشرية أثناء العمليات الحساسة.""", category="تقنية وصحة", author="د. سامي الجمال", image="https://images.unsplash.com/photo-1526374965328-7f61d4dc18c5?w=600&auto=format&fit=crop&q=60", summary="يستعرض المقال كيف يُحدث الذكاء الاصطناعي ثورة في قطاع الرعاية الصحية من خلال التشخيص الدقيق للأمراض وتطوير الأدوية وتوجيه الروبوتات الجراحية." ), models.Article( id=2, title="أسرار النوم الصحي وأثره على الإنتاجية", content="""يعتقد الكثيرون أن النوم هو مجرد وقت مستقطع من اليوم للراحة، لكن الأبحاث الحديثة تؤكد أنه عملية حيوية بالغة الأهمية لتنظيف الدماغ من السموم المتراكمة طوال النهار. الحصول على 7 إلى 8 ساعات من النوم العميق ليلاً يساعد على تحسين الذاكرة قصيرة المدى وزيادة القدرة على التركيز واتخاذ القرارات الصائبة في اليوم التالي. على النقيض من ذلك، يؤدي الحرمان المزمن من النوم إلى تدهور الصحة النفسية وزيادة خطر الإصابة بأمراض القلب والسكري. للحصول على نوم مثالي، يُنصح بالابتعاد عن الشاشات الزرقاء قبل ساعة من النوم وتثبيت موعد النوم والاستيقاظ يومياً.""", category="نمط حياة وصحة", author="منى الصاوي", image="https://images.unsplash.com/photo-1511295742364-92767fa62d9f?w=600&auto=format&fit=crop&q=60", summary="يتناول المقال الأهمية البيولوجية للنوم الصحي في تحسين التركيز والذاكرة وحماية الصحة العامة، مع تقديم نصائح عملية لنوم أفضل." ), models.Article( id=3, title="استكشاف الكواكب البعيدة: هل سنصل إليها يوماً؟", content="""لطالما كان السفر عبر النجوم حلماً يراود البشرية منذ عقود. مع اكتشاف آلاف الكواكب خارج مجموعتنا الشمسية (Exoplanets)، بدأ العلماء في البحث عن كواكب تقع في النطاق الصالح للحياة (Goldilocks zone) حيث يمكن للماء السائل أن يتواجد. العقبة الكبرى التي تواجهنا هي المسافات الشاسعة؛ فأقرب كوكب يحتمل أن يكون صالحاً للحياة يبعد عنا حوالي 4 سنوات ضوئية، وهي مسافة تتطلب آلاف السنين للوصول إليها باستخدام تكنولوجيا الصواريخ الحالية. تجرى حالياً أبحاث حول محركات الدفع الضوئي والمركبات النانوية فائقة السرعة التي قد تمهد الطريق لإرسال أولى المسابر البشرية إلى تلك العوالم البعيدة خلال هذا القرن.""", category="علوم وفضاء", author="م. رامي كمال", image="https://images.unsplash.com/photo-1451187580459-43490279c0fa?w=600&auto=format&fit=crop&q=60", summary="يناقش المقال التحديات والآمال المتعلقة بالسفر لاستكشاف الكواكب البعيدة الصالحة للحياة خارج نظامنا الشمسي والتكنولوجيا المستقبلية المقترحة." ) ]
db.add_all(articles) db.commit() print("Database seeded successfully with test data!")
except Exception as e: print(f"Error seeding database: {e}") db.rollback() finally: db.close()
if __name__ == "__main__": seed_db().env.exampleAdded+3
.gitignoreAdded+9
DockerfileAdded+22
README.mdAdded+37
app/db/database.pyAdded+19
app/main.pyAdded+357
app/models/models.pyAdded+36
app/schemas/schemas.pyAdded+67
app/services/scraper.pyAdded+117
requirements.txtAdded+12
scripts/seed.pyAdded+73