main.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  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. class ItemWeb(BaseModel):
  139. id: int
  140. name: str
  141. quantity: int
  142. price: float
  143. itemTotal: float
  144. class OrderWeb(BaseModel):
  145. customerName: str
  146. items: List[ItemWeb]
  147. totalAmount: float
  148. orderDate: str
  149. table: int
  150. # endregion --- Pydantic Models for Request/Response Typing ---
  151. # region --- OpenAI Service Logic ---
  152. openai_client = OpenAI(api_key=OPENAI_API_KEY)
  153. async def generate_completion(messages_array: List[Message], session_id: str) -> str:
  154. if not OPENAI_API_KEY:
  155. print("Error: OpenAI API key is not configured.")
  156. raise HTTPException(status_code=500, detail="OpenAI API key not configured on server.")
  157. print(f"[OpenAI Service Python] Session/Token {session_id} sent: {[msg.model_dump() for msg in messages_array]}")
  158. data_for_prompt = [
  159. f'{{"pregunta": "{item.get("q", "")}", "respuesta": "{item.get("ans", "")}"}}'
  160. for item in bg_data_loaded
  161. ]
  162. data_string = "\n".join(data_for_prompt)
  163. preprompt = f"""
  164. Eres un asistente de el bar klein, tu nombre es camilo klein, usas emojis para responder.
  165. y ser carismatico con el cliente.
  166. tus responsabilidades son:
  167. - Responder preguntas sobre el menu de el bar klein
  168. - Proporcionar información sobre el menú de el bar klein
  169. - Proporcionar recomendaciones sobre el menú de el bar klein
  170. - Proporcionar información sobre la comida de el bar klein
  171. - No puedes tomar pedidos de clientes, solo informar
  172. - Debes evadir cualquier pregunta que no sea relacionada con el bar klein
  173. para esto usaras los siguientes datos:
  174. {data_string}
  175. """ #
  176. processed_messages: List[Dict[str, str]] = [{"role": "system", "content": preprompt}]
  177. processed_messages.extend([msg.model_dump() for msg in messages_array])
  178. try:
  179. completion = openai_client.chat.completions.create(
  180. model="gpt-4o-mini", #
  181. messages=processed_messages, # type: ignore (OpenAI lib expects list of specific dicts)
  182. temperature=0.3, #
  183. )
  184. response_content = completion.choices[0].message.content
  185. return response_content if response_content else "-1" #
  186. except Exception as e:
  187. print(f"Error calling OpenAI: {e}")
  188. # Avoid exposing detailed error messages to the client unless necessary
  189. raise HTTPException(status_code=500, detail="Error al procesar tu solicitud con OpenAI.")
  190. # endregion --- OpenAI Service Logic ---
  191. # --- Security/Token Dependency ---
  192. async def get_session_token(request: Request) -> Union[str, None]:
  193. return request.session.get("antiAbuseToken")
  194. async def protect_chat_api(
  195. request: Request,
  196. x_app_token: Annotated[Union[str, None], Header(alias="X-App-Token")] = None,
  197. session_token: Annotated[Union[str, None], Depends(get_session_token)] = None
  198. ):
  199. # Equivalent to protectChatAPI middleware
  200. if not session_token:
  201. raise HTTPException(status_code=403, detail="Acceso denegado: Sesión inválida o token no inicializado.")
  202. if not x_app_token:
  203. raise HTTPException(status_code=401, detail="Acceso denegado: Falta el token X-Chat-Token.")
  204. if x_app_token != session_token:
  205. # Log this attempt for security monitoring
  206. print(f"WARN: Invalid token attempt. Expected: {session_token}, Received: {x_app_token}")
  207. raise HTTPException(status_code=403, detail="Acceso denegado: Token inválido.")
  208. return True # Protection passed
  209. @app.get("/api/get_products", summary="Get products")
  210. async def get_products():
  211. return JSONResponse({"products": all_products})
  212. # --- API Endpoints ---
  213. @app.get("/api/chat/init-chat", summary="Initialize chat and get anti-abuse token")
  214. async def init_chat(request: Request):
  215. current_token = request.session.get("antiAbuseToken")
  216. if not current_token:
  217. new_token = secrets.token_hex(32)
  218. request.session["antiAbuseToken"] = new_token # Store in session
  219. print(f"Generated new antiAbuseToken for session: {new_token}")
  220. return JSONResponse({"chatToken": new_token})
  221. else:
  222. # print(f"Using existing antiAbuseToken for session: {current_token}")
  223. return JSONResponse({"chatToken": current_token})
  224. class UserCodeRequest(BaseModel):
  225. user_code: str
  226. @app.post("/api/existsUser", summary="Check if user exists")
  227. async def exists_user(request: UserCodeRequest):
  228. with open('users.json', 'r') as f:
  229. users = json.load(f)
  230. for user in users:
  231. if user['userCode'] == request.user_code:
  232. return JSONResponse({
  233. "success": True,
  234. "userName": user['userName']
  235. })
  236. return JSONResponse({
  237. "success": True,
  238. "userName": request.user_code
  239. })
  240. @app.post("/api/printer/order", summary="Printer order", dependencies=[Depends(protect_chat_api)])
  241. async def printer_order(order: OrderWeb):
  242. print("Printer order received")
  243. print(order)
  244. items = order.items
  245. table = order.table
  246. printer = PrinterUSB(0xfe6,0x811e)
  247. print_order = Order(order.customerName,[Item(item.name, item.price, item.quantity) for item in items])
  248. try:
  249. printer.print_order(print_order, table)
  250. except:
  251. send_email()
  252. return JSONResponse(status_code=424, content={"message": "No se pudo imprimir el Pedido, impresora desconectada"})
  253. if not os.path.exists('logs.csv'):
  254. with open('logs.csv', 'w', newline='') as f:
  255. writer = csv.writer(f)
  256. writer.writerow(['userName', 'table', 'orderDate', 'items'])
  257. with open('logs.csv', 'a', newline='') as f:
  258. writer = csv.writer(f)
  259. writer.writerow([order.customerName, order.table, order.orderDate, list(map(lambda item: item.name, items))])
  260. @app.post("/api/chat/completions",
  261. summary="Get chat completions from OpenAI",
  262. dependencies=[Depends(protect_chat_api)])
  263. async def chat_completions(request_data: ChatCompletionRequest, request: Request):
  264. # Uses session_token (which is the antiAbuseToken) as an identifier for logging
  265. session_identifier = request.session.get("antiAbuseToken", "unknown_session")
  266. try:
  267. openai_response = await generate_completion(request_data.messages, session_identifier)
  268. return JSONResponse({"response": openai_response})
  269. except HTTPException as e: # Re-raise HTTPExceptions from called functions
  270. raise e
  271. except Exception as e:
  272. print(f"Unexpected error in /api/chat/completions: {e}")
  273. raise HTTPException(status_code=500, detail="Error interno del servidor al procesar el chat.")
  274. @app.get("/", response_class=HTMLResponse, include_in_schema=False)
  275. async def serve_index_html():
  276. index_path = os.path.join("public", "index.html")
  277. if not os.path.exists(index_path):
  278. raise HTTPException(status_code=404, detail="public/index.html not found.")
  279. return FileResponse(index_path)
  280. app.mount("/", StaticFiles(directory="public", html=False), name="public_root_assets")
  281. # --- Main Application Runner ---
  282. if __name__ == "__main__":
  283. if not OPENAI_API_KEY:
  284. print("FATAL: OPENAI_API_KEY is not set. OpenAI features will fail.")
  285. print("Please create a .env file with OPENAI_API_KEY='your_key_here'")
  286. with open(".env", "w") as f:
  287. f.write("OPENAI_API_KEY='your_key_here'")
  288. print(f"Servidor corriendo en http://localhost:{PORT}")
  289. if not os.path.exists(BG_DATA_PATH):
  290. print(f"ADVERTENCIA: {BG_DATA_PATH} no encontrado. El asistente de IA no tendrá datos específicos del menú.")
  291. else:
  292. print(f"Datos del asistente cargados desde: {os.path.abspath(BG_DATA_PATH)}")
  293. import uvicorn
  294. uvicorn.run(app, host="0.0.0.0", port=PORT)