CoolFace
Apppublic

NeuralNodeAI/sentic-ai-backend

sourceHugging Faceupdated 8mo agoView on Hugging Face
0likes
main.py85 linesDownload Raw Back to root
1from fastapi import FastAPI2from fastapi.responses import HTMLResponse  3from pydantic import BaseModel4from fastapi.middleware.cors import CORSMiddleware5from transformers import pipeline6from langdetect import detect7import re8 9# إنشاء تطبيق الـ FastAPI10app = FastAPI()11 12# إضافة نظام الـ CORS13app.add_middleware(14    CORSMiddleware,15    allow_origins=["*"],16    allow_methods=["*"],17    allow_headers=["*"],18)19 20# تعريف الموديلات (Pipelines)21print("Loading models... please wait.") # رسالة عشان تعرف في اللوجز إنه بيحمل22sentiment_model = pipeline("sentiment-analysis")23topic_model = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")24 25# تعريف شكل البيانات26class UserRequest(BaseModel):27    text: str28 29# 2. تعديل الـ Home ليعرض ملف HTML بدلاً من رسالة JSON30@app.get("/", response_class=HTMLResponse)31def home():32    # هنا السيرفر بيقرأ ملف index.html اللي أنت رفعته وبيرجعه للمتصفح33    try:34        with open("index.html", "r", encoding="utf-8") as f:35            return f.read()36    except FileNotFoundError:37        return "<h1>Error: index.html not found. Please upload the file.</h1>"38 39@app.post("/analyze")40def analyze_content(request: UserRequest):41    # تنظيف النص42    input_text = request.text.strip()43 44    # التحقق من المدخلات45    if not input_text or not re.search('[a-zA-Zا-ي]', input_text):46        return {"error": "Invalid input. Please provide a clear and meaningful text for analysis."}47 48    # تحليل المشاعر49    sentiment_data = sentiment_model(input_text)[0]50    sentiment_label = sentiment_data['label']51    52    # صياغة الرد53    if sentiment_label == "NEGATIVE":54        sentiment_feedback = "We detected a negative tone. Remember that challenges are just opportunities for growth."55    else:56        sentiment_feedback = "We detected a positive tone. Your optimism is truly inspiring and adds great value."57 58    # كشف اللغة59    try:60        language_code = detect(input_text)61    except:62        language_code = "Unknown"63 64    # تصنيف الموضوع65    possible_categories = ["Politics", "Sports", "Technology", "Economy", "Health"]66    classification_output = topic_model(input_text, candidate_labels=possible_categories)67    dominant_topic = classification_output['labels'][0]68 69    # تجميع النتائج70    formatted_response = (71        f"Content Analysis: This text is classified under [{dominant_topic}]. "72        f"Detected Language: [{language_code}]. "73        f"AI Insight: {sentiment_feedback}"74    )75 76    return {77        "status": "success",78        "result": formatted_response,79        "raw_data": {80            "category": dominant_topic,81            "language": language_code,82            "sentiment": sentiment_label83        }84    }85