Spaces:
Sleeping
Sleeping
feat: implement main Flask app with AI-driven recommendation logic
Browse files
app.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import google.generativeai as genai
|
| 2 |
+
import os
|
| 3 |
+
from flask import Flask, render_template
|
| 4 |
+
from user_data import get_user_history
|
| 5 |
+
from book_recommendations import (
|
| 6 |
+
recommend_fiction,
|
| 7 |
+
recommend_non_fiction,
|
| 8 |
+
recommend_science
|
| 9 |
+
)
|
| 10 |
+
|
| 11 |
+
app = Flask(__name__)
|
| 12 |
+
|
| 13 |
+
# Configurar a chave de API
|
| 14 |
+
GOOGLE_API_KEY = os.environ.get('GOOGLE_API_KEY')
|
| 15 |
+
genai.configure(api_key=GOOGLE_API_KEY)
|
| 16 |
+
|
| 17 |
+
# Definir o modelo generativo com as funções disponíveis
|
| 18 |
+
magical_if = genai.GenerativeModel(
|
| 19 |
+
"gemini-1.5-flash",
|
| 20 |
+
tools=[
|
| 21 |
+
recommend_fiction,
|
| 22 |
+
recommend_non_fiction,
|
| 23 |
+
recommend_science
|
| 24 |
+
]
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
def ia_decision(user_id, history):
|
| 28 |
+
business_rules = """
|
| 29 |
+
Analise o histórico de compras do usuário e decida qual categoria de livros recomendar.
|
| 30 |
+
Regras:
|
| 31 |
+
1. Se o usuário comprou mais livros de ficção, recomende ficção.
|
| 32 |
+
2. Se o usuário comprou mais livros de não ficção, recomende não ficção.
|
| 33 |
+
3. Se o usuário demonstrou interesse em ciência, recomende ciência.
|
| 34 |
+
4. Caso contrário, ofereça uma recomendação geral de ficção.
|
| 35 |
+
"""
|
| 36 |
+
user_decision = magical_if.start_chat(enable_automatic_function_calling=True)
|
| 37 |
+
response = user_decision.send_message(
|
| 38 |
+
f"Histórico do usuário {user_id}: {history}; Regras de negócio: {business_rules}"
|
| 39 |
+
)
|
| 40 |
+
return response.text
|
| 41 |
+
|
| 42 |
+
@app.route('/recommend/<int:user_id>')
|
| 43 |
+
def recommend(user_id):
|
| 44 |
+
history = get_user_history(user_id)
|
| 45 |
+
if not history:
|
| 46 |
+
return "Usuário não encontrado", 404
|
| 47 |
+
ia_response = ia_decision(user_id, history)
|
| 48 |
+
return render_template('recommendation.html', user_id=user_id, message=ia_response)
|
| 49 |
+
|
| 50 |
+
if __name__ == '__main__':
|
| 51 |
+
app.run(debug=True)
|