-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
90 lines (64 loc) · 2.82 KB
/
Copy pathapp.py
File metadata and controls
90 lines (64 loc) · 2.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import os
import json
from flask import Flask, request, jsonify, render_template
from groq import Groq
from dotenv import load_dotenv
load_dotenv()
app = Flask(__name__)
client = Groq(api_key=os.environ.get("GROQ_API_KEY"))
GROQ_MODEL = "llama-3.1-8b-instant"
def build_prompt(text: str) -> str:
# Prompt in inglese: i modelli Llama performano meglio in inglese
# anche quando il testo da analizzare è in un'altra lingua.
return f"""Analyze the following text and respond ONLY with a valid JSON object.
No markdown, no backticks, no additional text.
Required schema: {{"sentiment": "positive|negative|neutral",
"sentiment_score": float 0-1, "emotion": "joy|sadness|anger|fear|surprise|disgust",
"emotion_intensity": float 0-1, "keywords": [max 5 keywords],
"summary": "string max 20 words"}}
Text to analyze: {text}"""
def parse_groq_response(content: str) -> dict:
# Il modello a volte aggiunge backtick markdown nonostante le istruzioni — li rimuoviamo
cleaned = content.strip()
if cleaned.startswith("```"):
lines = cleaned.split("\n")
cleaned = "\n".join(lines[1:-1] if lines[-1].strip() == "```" else lines[1:])
result = json.loads(cleaned)
required_fields = ["sentiment", "sentiment_score", "emotion", "emotion_intensity", "keywords", "summary"]
for field in required_fields:
if field not in result:
raise ValueError(f"Campo mancante nella risposta AI: {field}")
return result
@app.route("/")
def index():
return render_template("index.html")
@app.route("/api/analyze", methods=["POST"])
def analyze():
data = request.get_json(silent=True)
if not data or "text" not in data:
return jsonify({"error": "Parametro 'text' mancante nel body della richiesta"}), 400
text = data["text"].strip()
if len(text) < 10:
return jsonify({"error": "Il testo deve contenere almeno 10 caratteri"}), 400
if len(text) > 1000:
return jsonify({"error": "Il testo non può superare 1000 caratteri"}), 400
try:
prompt = build_prompt(text)
completion = client.chat.completions.create(
model=GROQ_MODEL,
messages=[{"role": "user", "content": prompt}],
temperature=0.1,
max_tokens=300,
)
raw_content = completion.choices[0].message.content
result = parse_groq_response(raw_content)
return jsonify(result)
except json.JSONDecodeError as e:
return jsonify({"error": f"Risposta AI non valida (JSON malformato): {str(e)}"}), 500
except ValueError as e:
return jsonify({"error": str(e)}), 500
except Exception as e:
return jsonify({"error": f"Errore durante la chiamata alla Groq API: {str(e)}"}), 500
if __name__ == "__main__":
print("MoodMapper avviato su http://localhost:5001")
app.run(debug=True, port=5001)