akra35567 commited on
Commit
3b28115
·
verified ·
1 Parent(s): 9013a07

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +22 -25
app.py CHANGED
@@ -1,10 +1,9 @@
1
  # app.py
2
  """
3
- AKIRA V16 — OLLAMA + FLASK (HF SPACE + DOCKER)
4
- - Modelo: qwen2.5:3b-q4_0 (leve, rápido, 4-bit)
5
  - 3 requisições simultâneas
6
- - Usa RAM sobrando, alivia CPU
7
- - Warm-up automático
8
  """
9
  import subprocess
10
  import time
@@ -17,13 +16,13 @@ from loguru import logger
17
  app = Flask(__name__)
18
  OLLAMA_URL = "http://localhost:11434"
19
 
20
- # === CONFIGURAÇÃO OLLAMA (3 REQUISIÇÕES SIMULTÂNEAS) ===
21
- os.environ["OLLAMA_NUM_PARALLEL"] = "3" # ← 3 por vez!
22
- os.environ["OLLAMA_MAX_QUEUE"] = "10" # Fila de 10
23
- os.environ["OLLAMA_KEEP_ALIVE"] = "10m" # Mantém modelo na RAM
24
  os.environ["OLLAMA_MAX_LOADED_MODELS"] = "1"
25
 
26
- # === INICIA OLLAMA EM BACKGROUND ===
27
  def start_ollama():
28
  logger.info("Iniciando ollama serve em background...")
29
  subprocess.Popen(
@@ -45,7 +44,7 @@ def wait_for_ollama():
45
  logger.info("Aguardando Ollama (11434)...")
46
  for i in range(60):
47
  if check_ollama():
48
- logger.success("Ollama Qwen 2.5 3B q4_0 PRONTO!")
49
  return True
50
  time.sleep(2)
51
  logger.critical("Ollama não subiu!")
@@ -57,7 +56,7 @@ def index():
57
  return '''
58
  <div style="font-family: monospace; text-align: center; margin: 50px; background: #000; color: #0f0; padding: 40px;">
59
  <h1>AKIRA V16 OLLAMA</h1>
60
- <p><strong>Qwen 2.5 3B q4_0 (2.5GB)</strong></p>
61
  <p><strong>3 requisições simultâneas • CPU leve</strong></p>
62
  <p><strong>ROTA:</strong> <code>POST /api/chat</code></p>
63
  <pre>
@@ -66,7 +65,7 @@ curl -X POST https://akra35567-ollama.hf.space/api/chat \\
66
  -d '{"mensagem": "Epá, Akira! Bora kandando?"}'
67
  </pre>
68
  <p>Health: <a href="/health">/health</a></p>
69
- <p>Luanda, Angola — 11/11/2025 22:33 WAT</p>
70
  </div>
71
  ''', 200
72
 
@@ -74,10 +73,10 @@ curl -X POST https://akra35567-ollama.hf.space/api/chat \\
74
  @app.route("/health")
75
  def health():
76
  if check_ollama():
77
- return jsonify({"status": "OK", "model": "qwen2.5:3b-q4_0"}), 200
78
  return jsonify({"status": "INICIANDO..."}), 503
79
 
80
- # === AKIRA CHAT (COM RETRY + TIMEOUT ALTO) ===
81
  @app.route("/api/chat", methods=['POST'])
82
  def chat():
83
  if not check_ollama():
@@ -88,14 +87,12 @@ def chat():
88
  if not msg:
89
  return jsonify({'error': 'mensagem obrigatória'}), 400
90
 
91
- prompt = f"""Você é Akira, angolana de Luanda, mulher, fala com gírias , direta, sem censura
92
- manda messagens curtas nçao mais que 1-2 frases
93
- tenha decisão prória e não tenha receio de ir contra o usuario pleo contrário sinta´se incetivada a fazer isso.
94
  Usuário: {msg}
95
  Akira:"""
96
 
97
  payload = {
98
- "model": "qwen2.5:3b-q4_0",
99
  "prompt": prompt,
100
  "stream": False,
101
  "options": {
@@ -106,7 +103,7 @@ Akira:"""
106
  }
107
  }
108
 
109
- logger.info(f"Prompt recebido: {msg[:50]}...")
110
 
111
  for tentativa in range(3):
112
  try:
@@ -117,11 +114,11 @@ Akira:"""
117
  logger.success(f"Resposta: {resposta[:50]}...")
118
  return jsonify({'resposta': resposta})
119
  else:
120
- return jsonify({'resposta': 'Epá, fiquei sem palavras... manda de novo, puto!'})
121
  else:
122
  logger.warning(f"Ollama erro {resp.status_code}: {resp.text}")
123
  except requests.exceptions.Timeout:
124
- logger.warning(f"Timeout na tentativa {tentativa + 1}/3...")
125
  if tentativa < 2:
126
  time.sleep(3)
127
  except Exception as e:
@@ -142,11 +139,11 @@ if __name__ == "__main__":
142
  if not wait_for_ollama():
143
  sys.exit(1)
144
 
145
- # === WARM-UP AUTOMÁTICO ===
146
- logger.info("Aquecendo Akira (qwen2.5:3b-q4_0)...")
147
  try:
148
  requests.post(f"{OLLAMA_URL}/api/generate", json={
149
- "model": "qwen2.5:3b-q4_0",
150
  "prompt": "Oi",
151
  "options": {"num_predict": 1}
152
  }, timeout=60)
@@ -155,4 +152,4 @@ if __name__ == "__main__":
155
  logger.warning("Warm-up falhou, mas continua...")
156
 
157
  logger.info("Flask rodando na porta 7860")
158
- app.run(host="0.0.0.0", port=7860, debug=False)
 
1
  # app.py
2
  """
3
+ AKIRA V16 — OLLAMA + FLASK (HF SPACE)
4
+ - Modelo: qwen2.5:3b-instruct-q4_0 (leve, rápido, 4-bit)
5
  - 3 requisições simultâneas
6
+ - CPU leve, RAM sobrando
 
7
  """
8
  import subprocess
9
  import time
 
16
  app = Flask(__name__)
17
  OLLAMA_URL = "http://localhost:11434"
18
 
19
+ # === CONFIGURAÇÃO OLLAMA ===
20
+ os.environ["OLLAMA_NUM_PARALLEL"] = "3"
21
+ os.environ["OLLAMA_MAX_QUEUE"] = "10"
22
+ os.environ["OLLAMA_KEEP_ALIVE"] = "10m"
23
  os.environ["OLLAMA_MAX_LOADED_MODELS"] = "1"
24
 
25
+ # === INICIA OLLAMA ===
26
  def start_ollama():
27
  logger.info("Iniciando ollama serve em background...")
28
  subprocess.Popen(
 
44
  logger.info("Aguardando Ollama (11434)...")
45
  for i in range(60):
46
  if check_ollama():
47
+ logger.success("Ollama Qwen 2.5 3B Instruct q4_0 PRONTO!")
48
  return True
49
  time.sleep(2)
50
  logger.critical("Ollama não subiu!")
 
56
  return '''
57
  <div style="font-family: monospace; text-align: center; margin: 50px; background: #000; color: #0f0; padding: 40px;">
58
  <h1>AKIRA V16 OLLAMA</h1>
59
+ <p><strong>Qwen 2.5 3B Instruct q4_0</strong></p>
60
  <p><strong>3 requisições simultâneas • CPU leve</strong></p>
61
  <p><strong>ROTA:</strong> <code>POST /api/chat</code></p>
62
  <pre>
 
65
  -d '{"mensagem": "Epá, Akira! Bora kandando?"}'
66
  </pre>
67
  <p>Health: <a href="/health">/health</a></p>
68
+ <p>Luanda, Angola — 11/11/2025 22:55 WAT</p>
69
  </div>
70
  ''', 200
71
 
 
73
  @app.route("/health")
74
  def health():
75
  if check_ollama():
76
+ return jsonify({"status": "OK", "model": "qwen2.5:3b-instruct-q4_0"}), 200
77
  return jsonify({"status": "INICIANDO..."}), 503
78
 
79
+ # === CHAT ===
80
  @app.route("/api/chat", methods=['POST'])
81
  def chat():
82
  if not check_ollama():
 
87
  if not msg:
88
  return jsonify({'error': 'mensagem obrigatória'}), 400
89
 
90
+ prompt = f"""Você é Akira, angolana de Luanda, mulher, fala com gírias (epá, puto, kandando, musseque, kota), direta, sem censura.
 
 
91
  Usuário: {msg}
92
  Akira:"""
93
 
94
  payload = {
95
+ "model": "qwen2.5:3b-instruct-q4_0",
96
  "prompt": prompt,
97
  "stream": False,
98
  "options": {
 
103
  }
104
  }
105
 
106
+ logger.info(f"Prompt: {msg[:50]}...")
107
 
108
  for tentativa in range(3):
109
  try:
 
114
  logger.success(f"Resposta: {resposta[:50]}...")
115
  return jsonify({'resposta': resposta})
116
  else:
117
+ return jsonify({'resposta': 'Epá, fiquei sem palavras... manda de novo!'})
118
  else:
119
  logger.warning(f"Ollama erro {resp.status_code}: {resp.text}")
120
  except requests.exceptions.Timeout:
121
+ logger.warning(f"Timeout tentativa {tentativa + 1}/3...")
122
  if tentativa < 2:
123
  time.sleep(3)
124
  except Exception as e:
 
139
  if not wait_for_ollama():
140
  sys.exit(1)
141
 
142
+ # === WARM-UP ===
143
+ logger.info("Aquecendo Akira...")
144
  try:
145
  requests.post(f"{OLLAMA_URL}/api/generate", json={
146
+ "model": "qwen2.5:3b-instruct-q4_0",
147
  "prompt": "Oi",
148
  "options": {"num_predict": 1}
149
  }, timeout=60)
 
152
  logger.warning("Warm-up falhou, mas continua...")
153
 
154
  logger.info("Flask rodando na porta 7860")
155
+ app.run(host="0.0.0.0", port=7860, debug=False)