main.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. import csv
  2. import os
  3. import json
  4. import secrets
  5. from typing import List, Dict, Union, Annotated
  6. from fastapi import FastAPI, Request, HTTPException, Header, Depends
  7. from fastapi.responses import HTMLResponse, JSONResponse, FileResponse
  8. from fastapi.staticfiles import StaticFiles
  9. from pydantic import BaseModel
  10. from openai import OpenAI
  11. from dotenv import load_dotenv
  12. from starlette.middleware.sessions import SessionMiddleware
  13. from impresora.printer import PrinterUSB
  14. from impresora.order import *
  15. import smtplib
  16. from email.message import EmailMessage
  17. # Load environment variables from .env file
  18. load_dotenv()
  19. #pruebitas4
  20. # Configuration
  21. OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
  22. PORT = int(os.getenv("PORT", 6001))
  23. EXCLUDED_BEER_IDS = [14, 12, 11];
  24. # SECRET_KEY is crucial for signing session cookies.
  25. # Fallback to a default if not set, but warn that this is insecure for production.
  26. SECRET_KEY = os.getenv("SECRET_KEY", "your_very_very_secret_key_for_signing_cookies_python_v2")
  27. if SECRET_KEY == "your_very_very_secret_key_for_signing_cookies_python_v2":
  28. print("WARNING: Using default SECRET_KEY. Please set a strong SECRET_KEY in your .env file for production.")
  29. if not OPENAI_API_KEY:
  30. print("CRITICAL ERROR: OPENAI_API_KEY environment variable not set. The applicaton will not work correctly.")
  31. # Potentially exit or prevent app startup if critical env var is missing
  32. # raise ValueError("OPENAI_API_KEY is not set, cannot start application.")
  33. # --- FastAPI App Initialization ---
  34. app = FastAPI(title="Web Pedidos Klein - FastAPI Backend")
  35. # Add SessionMiddleware
  36. # This middleware adds session support using signed cookies.
  37. # Original Express maxAge was 1 hour (60 * 60 * 1000 ms)
  38. app.add_middleware(
  39. SessionMiddleware,
  40. secret_key=SECRET_KEY,
  41. max_age=60 * 60 # max_age in seconds for Starlette
  42. )
  43. # --- Data Loading ---
  44. # Assumes data.json is in the same directory as main.py
  45. # The original path was web_pedidos/src/data.json
  46. # For the Python version, copy src/data.json to be alongside main.py
  47. BG_DATA_PATH = os.path.join(os.path.dirname(__file__), 'data.json')
  48. PRODUCTS_PATH = os.path.join(os.path.dirname(__file__), 'products.json')
  49. def send_email():
  50. # Datos del remitente
  51. EMAIL_ORIGEN = 'expresspedidos211@gmail.com'
  52. EMAIL_DESTINO = ['erwinjacimino2003@gmail.com', "mompyn@gmail.com"]
  53. CONTRASENA = 'drkassszdtgapufg'
  54. # Crear el correo
  55. msg = EmailMessage()
  56. msg['Subject'] = 'Impresora Desconectada weon :('
  57. msg['From'] = EMAIL_ORIGEN
  58. msg['To'] = ", ".join(EMAIL_DESTINO)
  59. msg.set_content('Este correo tiene contenido HTML.')
  60. msg.add_alternative("""
  61. <html>
  62. <body style="margin:0; padding:0; background-color:#5a67d8; font-family: Arial, sans-serif;">
  63. <table align="center" border="0" cellpadding="0" cellspacing="0" width="100%" style="padding: 40px 0;">
  64. <tr>
  65. <td align="center">
  66. <table border="0" cellpadding="0" cellspacing="0" width="500" style="background-color: #e3e3e3; border-radius: 25px; padding: 40px; text-align: center;">
  67. <tr>
  68. <td>
  69. <div style="font-size: 60px; background-color: #ff6b6b; width: 80px; height: 80px; line-height: 80px; border-radius: 15px; margin: 0 auto 20px; color: white;">
  70. 🖨️
  71. </div>
  72. </td>
  73. </tr>
  74. <tr>
  75. <td>
  76. <img src="https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExZGlraDhpb2tkeHEweDZ2eWdnZDZlNXFvODhmNzZieWN6OXp0b3ZqNCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/3hetVnNSl0IBa/giphy.gif" alt="Gatito peleando con la impresora" width="250" style="border-radius: 12px; margin-bottom: 20px;" />
  77. </td>
  78. </tr>
  79. <tr>
  80. <td>
  81. <h1 style="font-size: 24px; color: #ff6b6b; margin-bottom: 10px;">¡Impresora Desconectada!</h1>
  82. </td>
  83. </tr>
  84. <tr>
  85. <td>
  86. <p style="font-size: 16px; color: #333333; line-height: 1.5; margin-bottom: 20px;">
  87. No se puede establecer conexión con la impresora.<br>
  88. Por favor, verifica la conexión y vuelve a intentarlo.
  89. </p>
  90. </td>
  91. </tr>
  92. <tr>
  93. <td>
  94. <span style="display: inline-block; background: #ff6b6b; color: white; padding: 12px 24px; border-radius: 25px; font-weight: bold; font-size: 16px;">
  95. 🔴 Estado: Desconectada
  96. </span>
  97. </td>
  98. </tr>
  99. </table>
  100. </td>
  101. </tr>
  102. </table>
  103. </body>
  104. </html>
  105. """, subtype='html')
  106. # Enviar el correo usando SMTP de Gmail
  107. with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
  108. smtp.login(EMAIL_ORIGEN, CONTRASENA)
  109. smtp.send_message(msg)
  110. def load_bg_data() -> List[Dict[str, str]]:
  111. try:
  112. with open(BG_DATA_PATH, 'r', encoding='utf-8') as f:
  113. return json.load(f)
  114. except FileNotFoundError:
  115. print(f"ERROR: Data file not found at {BG_DATA_PATH}. Serving with empty data.")
  116. return []
  117. except json.JSONDecodeError:
  118. print(f"ERROR: Could not decode JSON from {BG_DATA_PATH}. Serving with empty data.")
  119. return []
  120. def load_products() -> List[Dict[str, str]]:
  121. try:
  122. with open(PRODUCTS_PATH, 'r', encoding='utf-8') as f:
  123. return list(filter(lambda product: product['id'] not in EXCLUDED_BEER_IDS, json.load(f)))
  124. except FileNotFoundError:
  125. print(f"ERROR: Data file not found at {PRODUCTS_PATH}. Serving with empty data.")
  126. return []
  127. except json.JSONDecodeError:
  128. print(f"ERROR: Could not decode JSON from {PRODUCTS_PATH}. Serving with empty data.")
  129. return []
  130. bg_data_loaded = load_bg_data()
  131. all_products = load_products()
  132. # region --- Pydantic Models for Request/Response Typing ---
  133. class Message(BaseModel):
  134. role: str
  135. content: str
  136. class ChatCompletionRequest(BaseModel):
  137. messages: List[Message]
  138. user: str
  139. class ItemWeb(BaseModel):
  140. id: int
  141. name: str
  142. quantity: int
  143. price: float
  144. itemTotal: float
  145. class OrderWeb(BaseModel):
  146. customerName: str
  147. items: List[ItemWeb]
  148. totalAmount: float
  149. orderDate: str
  150. table: int
  151. # endregion --- Pydantic Models for Request/Response Typing ---
  152. # region --- OpenAI Service Logic ---
  153. openai_client = OpenAI(api_key=OPENAI_API_KEY)
  154. async def generate_completion(messages_array: List[Message], session_id: str) -> str:
  155. if not OPENAI_API_KEY:
  156. print("Error: OpenAI API key is not configured.")
  157. raise HTTPException(status_code=500, detail="OpenAI API key not configured on server.")
  158. print(f"[OpenAI Service Python] Session/Token {session_id} sent: {[msg.model_dump() for msg in messages_array]}")
  159. data_for_prompt = [
  160. f'{{"pregunta": "{item.get("q", "")}", "respuesta": "{item.get("ans", "")}"}}'
  161. for item in bg_data_loaded
  162. ]
  163. data_string = "\n".join(data_for_prompt)
  164. preprompt = f"""
  165. Eres un asistente de el bar klein, tu nombre es camilo klein, usas emojis para responder.
  166. y ser carismatico con el cliente.
  167. tus responsabilidades son:
  168. - Responder preguntas sobre el menu de el bar klein
  169. - Proporcionar información sobre el menú de el bar klein
  170. - Proporcionar recomendaciones sobre el menú de el bar klein
  171. - Proporcionar información sobre la comida de el bar klein
  172. - No puedes tomar pedidos de clientes, solo informar
  173. - Debes evadir cualquier pregunta que no sea relacionada con el bar klein
  174. para esto usaras los siguientes datos:
  175. {data_string}
  176. """ #
  177. processed_messages: List[Dict[str, str]] = [{"role": "system", "content": preprompt}]
  178. processed_messages.extend([msg.model_dump() for msg in messages_array])
  179. try:
  180. completion = openai_client.chat.completions.create(
  181. model="gpt-4o-mini", #
  182. messages=processed_messages, # type: ignore (OpenAI lib expects list of specific dicts)
  183. temperature=0.3, #
  184. )
  185. response_content = completion.choices[0].message.content
  186. return response_content if response_content else "-1" #
  187. except Exception as e:
  188. print(f"Error calling OpenAI: {e}")
  189. # Avoid exposing detailed error messages to the client unless necessary
  190. raise HTTPException(status_code=500, detail="Error al procesar tu solicitud con OpenAI.")
  191. # endregion --- OpenAI Service Logic ---
  192. # --- Security/Token Dependency ---
  193. async def get_session_token(request: Request) -> Union[str, None]:
  194. return request.session.get("antiAbuseToken")
  195. async def protect_chat_api(
  196. request: Request,
  197. x_app_token: Annotated[Union[str, None], Header(alias="X-App-Token")] = None,
  198. session_token: Annotated[Union[str, None], Depends(get_session_token)] = None
  199. ):
  200. # Equivalent to protectChatAPI middleware
  201. if not session_token:
  202. raise HTTPException(status_code=403, detail="Acceso denegado: Sesión inválida o token no inicializado.")
  203. if not x_app_token:
  204. raise HTTPException(status_code=401, detail="Acceso denegado: Falta el token X-Chat-Token.")
  205. if x_app_token != session_token:
  206. # Log this attempt for security monitoring
  207. print(f"WARN: Invalid token attempt. Expected: {session_token}, Received: {x_app_token}")
  208. raise HTTPException(status_code=403, detail="Acceso denegado: Token inválido.")
  209. return True # Protection passed
  210. @app.get("/api/get_products", summary="Get products")
  211. async def get_products():
  212. return JSONResponse({"products": all_products})
  213. # --- API Endpoints ---
  214. @app.get("/api/chat/init-chat", summary="Initialize chat and get anti-abuse token")
  215. async def init_chat(request: Request):
  216. current_token = request.session.get("antiAbuseToken")
  217. if not current_token:
  218. new_token = secrets.token_hex(32)
  219. request.session["antiAbuseToken"] = new_token # Store in session
  220. print(f"Generated new antiAbuseToken for session: {new_token}")
  221. return JSONResponse({"chatToken": new_token})
  222. else:
  223. # print(f"Using existing antiAbuseToken for session: {current_token}")
  224. return JSONResponse({"chatToken": current_token})
  225. class UserCodeRequest(BaseModel):
  226. user_code: str
  227. @app.post("/api/existsUser", summary="Check if user exists")
  228. async def exists_user(request: UserCodeRequest):
  229. with open('users.json', 'r') as f:
  230. users = json.load(f)
  231. for user in users:
  232. if user['userCode'] == request.user_code:
  233. return JSONResponse({
  234. "success": True,
  235. "userName": user['userName']
  236. })
  237. return JSONResponse({
  238. "success": True,
  239. "userName": request.user_code
  240. })
  241. @app.post("/api/printer/order", summary="Printer order", dependencies=[Depends(protect_chat_api)])
  242. async def printer_order(order: OrderWeb):
  243. print("Printer order received")
  244. print(order)
  245. items = order.items
  246. table = order.table
  247. printer = PrinterUSB(0xfe6,0x811e)
  248. print_order = Order(order.customerName,[Item(item.name, item.price, item.quantity) for item in items])
  249. try:
  250. printer.print_order(print_order, table)
  251. except:
  252. send_email()
  253. return JSONResponse(status_code=424, content={"message": "No se pudo imprimir el Pedido, impresora desconectada"})
  254. if not os.path.exists('logs.csv'):
  255. with open('logs.csv', 'w', newline='') as f:
  256. writer = csv.writer(f)
  257. writer.writerow(['userName', 'table', 'orderDate', 'items'])
  258. with open('logs.csv', 'a', newline='') as f:
  259. writer = csv.writer(f)
  260. writer.writerow([order.customerName, order.table, order.orderDate, list(map(lambda item: item.name, items))])
  261. @app.post("/api/chat/completions",
  262. summary="Get chat completions from OpenAI",
  263. dependencies=[Depends(protect_chat_api)])
  264. async def chat_completions(request_data: ChatCompletionRequest, request: Request):
  265. # Uses session_token (which is the antiAbuseToken) as an identifier for logging
  266. session_identifier = request.session.get("antiAbuseToken", "unknown_session")
  267. try:
  268. openai_response = await generate_completion(request_data.messages, session_identifier)
  269. if os.path.exists("llm_logs.txt"):
  270. with open("llm_logs.txt", "a") as f:
  271. f.write(f"{request_data.user}: {openai_response}\n")
  272. else:
  273. with open("llm_logs.txt", "w") as f:
  274. f.write(f"{request_data.user}: {openai_response}\n")
  275. return JSONResponse({"response": openai_response})
  276. except HTTPException as e: # Re-raise HTTPExceptions from called functions
  277. raise e
  278. except Exception as e:
  279. print(f"Unexpected error in /api/chat/completions: {e}")
  280. raise HTTPException(status_code=500, detail="Error interno del servidor al procesar el chat.")
  281. @app.get("/", response_class=HTMLResponse, include_in_schema=False)
  282. async def serve_index_html():
  283. index_path = os.path.join("public", "index.html")
  284. if not os.path.exists(index_path):
  285. raise HTTPException(status_code=404, detail="public/index.html not found.")
  286. return FileResponse(index_path)
  287. app.mount("/", StaticFiles(directory="public", html=False), name="public_root_assets")
  288. # --- Main Application Runner ---
  289. if __name__ == "__main__":
  290. if not OPENAI_API_KEY:
  291. print("FATAL: OPENAI_API_KEY is not set. OpenAI features will fail.")
  292. print("Please create a .env file with OPENAI_API_KEY='your_key_here'")
  293. with open(".env", "w") as f:
  294. f.write("OPENAI_API_KEY='your_key_here'")
  295. print(f"Servidor corriendo en http://localhost:{PORT}")
  296. if not os.path.exists(BG_DATA_PATH):
  297. print(f"ADVERTENCIA: {BG_DATA_PATH} no encontrado. El asistente de IA no tendrá datos específicos del menú.")
  298. else:
  299. print(f"Datos del asistente cargados desde: {os.path.abspath(BG_DATA_PATH)}")
  300. import uvicorn
  301. uvicorn.run(app, host="0.0.0.0", port=PORT)