code

375 views
Skip to first unread message

האלי הרשליקוביץ

unread,
Mar 26, 2025, 2:38:39 AMMar 26
to Python GCU Forum
# chatgpt_sentiment_bot.py
import json
import datetime
import os
import openai
from transformers import pipeline
from flask import Flask, request, jsonify

# אתחול Flask
app = Flask(__name__)

# הגדרת OpenAI API Key
openai.api_key = os.getenv("OPENAI_API_KEY")

# אתחול המודלים (עברית + אנגלית)
sentiment_en = pipeline("sentiment-analysis")
sentiment_he = pipeline("text-classification", model="onlplab/alephbert-base", tokenizer="onlplab/alephbert-base")

# פונקציה לזיהוי שפה (עברית או אנגלית)
def detect_language(text):
    return "he" if any("\u0590" <= char <= "\u05EA" for char in text) else "en"

# ניתוח רגשות לפי שפה
def analyze_sentiment(text):
    lang = detect_language(text)
    model = sentiment_he if lang == "he" else sentiment_en
    result = model(text)
    return result[0]

# שמירת השיחה לקובץ JSON
def save_chat_history(user_input, sentiment, gpt_response):
    history = {
        "timestamp": str(datetime.datetime.now()),
        "user_input": user_input,
        "sentiment": sentiment["label"],
        "confidence": sentiment["score"],
        "gpt_response": gpt_response
    }
    with open("chat_history.json", "a", encoding="utf-8") as file:
        json.dump(history, file, ensure_ascii=False)
        file.write("\n")

# פונקציה ליצירת תגובה מ-ChatGPT
def chat_with_gpt(user_input, sentiment):
    prompt = f"""
    אתה עוזר חכם שמגיב למשתמשים. ניתחת את הטקסט הבא:
   
    טקסט: "{user_input}"
    רגש: {sentiment['label']}
    ביטחון: {sentiment['score']:.4f}
   
    הגיב בצורה ידידותית, מבוססת על ניתוח הרגשות:
    """
    try:
        response = openai.ChatCompletion.create(
            model="gpt-4",
            messages=[{"role": "user", "content": prompt}]
        )
        return response.choices[0].message.content.strip()
    except Exception as e:
        print(f"שגיאה ב-ChatGPT: {e}")
        return "שגיאה במערכת, נסה שוב מאוחר יותר."

# נתיב API לצ'אט
@app.route("/chat", methods=["POST"])
def chat():
    data = request.json
    user_input = data.get("message")
    if not user_input:
        return jsonify({"error": "יש להזין הודעה"}), 400
   
    # ניתוח רגשות
    sentiment = analyze_sentiment(user_input)

    # קבלת תגובה מ-ChatGPT
    gpt_response = chat_with_gpt(user_input, sentiment)

    # שמירת השיחה
    save_chat_history(user_input, sentiment, gpt_response)

    return jsonify({
        "input": user_input,
        "sentiment": sentiment["label"],
        "confidence": round(sentiment["score"], 4),
        "response": gpt_response
    })

if __name__ == "__main__":
    print("🚀 הצ'אט מחובר ל-ChatGPT ומוכן לפעולה!")
    app.run(host="0.0.0.0", port=5000)
Reply all
Reply to author
Forward
0 new messages