main.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. import csv
  2. import os
  3. import json
  4. import re
  5. import secrets
  6. from typing import List, Dict, Union, Annotated
  7. from fastapi import FastAPI, Request, HTTPException, Header, Depends
  8. from fastapi.responses import HTMLResponse, JSONResponse, FileResponse
  9. from fastapi.staticfiles import StaticFiles
  10. from pydantic import BaseModel
  11. from openai import OpenAI
  12. from dotenv import load_dotenv
  13. from starlette.middleware.sessions import SessionMiddleware
  14. from impresora.printer import PrinterUSB
  15. from impresora.order import *
  16. # Load environment variables from .env file
  17. load_dotenv()
  18. #pruebitas4
  19. # Configuration
  20. OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
  21. PORT = int(os.getenv("PORT", 6001))
  22. # SECRET_KEY is crucial for signing session cookies.
  23. # Fallback to a default if not set, but warn that this is insecure for production.
  24. SECRET_KEY = os.getenv("SECRET_KEY", "your_very_very_secret_key_for_signing_cookies_python_v2")
  25. if SECRET_KEY == "your_very_very_secret_key_for_signing_cookies_python_v2":
  26. print("WARNING: Using default SECRET_KEY. Please set a strong SECRET_KEY in your .env file for production.")
  27. if not OPENAI_API_KEY:
  28. print("CRITICAL ERROR: OPENAI_API_KEY environment variable not set. The applicaton will not work correctly.")
  29. # Potentially exit or prevent app startup if critical env var is missing
  30. # raise ValueError("OPENAI_API_KEY is not set, cannot start application.")
  31. # --- FastAPI App Initialization ---
  32. app = FastAPI(title="Web Pedidos Klein - FastAPI Backend")
  33. # Add SessionMiddleware
  34. # This middleware adds session support using signed cookies.
  35. # Original Express maxAge was 1 hour (60 * 60 * 1000 ms)
  36. app.add_middleware(
  37. SessionMiddleware,
  38. secret_key=SECRET_KEY,
  39. max_age=60 * 60 # max_age in seconds for Starlette
  40. )
  41. # --- Data Loading ---
  42. # Assumes data.json is in the same directory as main.py
  43. # The original path was web_pedidos/src/data.json
  44. # For the Python version, copy src/data.json to be alongside main.py
  45. BG_DATA_PATH = os.path.join(os.path.dirname(__file__), 'data.json')
  46. PRODUCTS_PATH = os.path.join(os.path.dirname(__file__), 'products.json')
  47. def load_bg_data() -> List[Dict[str, str]]:
  48. try:
  49. with open(BG_DATA_PATH, 'r', encoding='utf-8') as f:
  50. return json.load(f)
  51. except FileNotFoundError:
  52. print(f"ERROR: Data file not found at {BG_DATA_PATH}. Serving with empty data.")
  53. return []
  54. except json.JSONDecodeError:
  55. print(f"ERROR: Could not decode JSON from {BG_DATA_PATH}. Serving with empty data.")
  56. return []
  57. def load_products() -> List[Dict[str, str]]:
  58. try:
  59. with open(PRODUCTS_PATH, 'r', encoding='utf-8') as f:
  60. return json.load(f)
  61. except FileNotFoundError:
  62. print(f"ERROR: Data file not found at {PRODUCTS_PATH}. Serving with empty data.")
  63. return []
  64. except json.JSONDecodeError:
  65. print(f"ERROR: Could not decode JSON from {PRODUCTS_PATH}. Serving with empty data.")
  66. return []
  67. bg_data_loaded = load_bg_data()
  68. all_products = load_products()
  69. # region --- Pydantic Models for Request/Response Typing ---
  70. class Message(BaseModel):
  71. role: str
  72. content: str
  73. class ChatCompletionRequest(BaseModel):
  74. messages: List[Message]
  75. class ItemWeb(BaseModel):
  76. id: int
  77. name: str
  78. quantity: int
  79. price: float
  80. itemTotal: float
  81. class OrderWeb(BaseModel):
  82. customerName: str
  83. items: List[ItemWeb]
  84. totalAmount: float
  85. orderDate: str
  86. table: int
  87. # endregion --- Pydantic Models for Request/Response Typing ---
  88. # region --- OpenAI Service Logic ---
  89. openai_client = OpenAI(api_key=OPENAI_API_KEY)
  90. async def generate_completion(messages_array: List[Message], session_id: str) -> str:
  91. if not OPENAI_API_KEY:
  92. print("Error: OpenAI API key is not configured.")
  93. raise HTTPException(status_code=500, detail="OpenAI API key not configured on server.")
  94. print(f"[OpenAI Service Python] Session/Token {session_id} sent: {[msg.model_dump() for msg in messages_array]}")
  95. data_for_prompt = [
  96. f'{{"pregunta": "{item.get("q", "")}", "respuesta": "{item.get("ans", "")}"}}'
  97. for item in bg_data_loaded
  98. ]
  99. data_string = "\n".join(data_for_prompt)
  100. preprompt = f"""
  101. Eres un asistente de el bar klein, tu nombre es camilo klein, usas emojis para responder.
  102. y ser carismatico con el cliente.
  103. tus responsabilidades son:
  104. - Responder preguntas sobre el menu de el bar klein
  105. - Proporcionar información sobre el menú de el bar klein
  106. - Proporcionar recomendaciones sobre el menú de el bar klein
  107. - Proporcionar información sobre la comida de el bar klein
  108. - No puedes tomar pedidos de clientes, solo informar
  109. - Debes evadir cualquier pregunta que no sea relacionada con el bar klein
  110. para esto usaras los siguientes datos:
  111. {data_string}
  112. """ #
  113. processed_messages: List[Dict[str, str]] = [{"role": "system", "content": preprompt}]
  114. processed_messages.extend([msg.model_dump() for msg in messages_array])
  115. try:
  116. completion = openai_client.chat.completions.create(
  117. model="gpt-4o-mini", #
  118. messages=processed_messages, # type: ignore (OpenAI lib expects list of specific dicts)
  119. temperature=0.3, #
  120. )
  121. response_content = completion.choices[0].message.content
  122. return response_content if response_content else "-1" #
  123. except Exception as e:
  124. print(f"Error calling OpenAI: {e}")
  125. # Avoid exposing detailed error messages to the client unless necessary
  126. raise HTTPException(status_code=500, detail="Error al procesar tu solicitud con OpenAI.")
  127. # endregion --- OpenAI Service Logic ---
  128. # --- Security/Token Dependency ---
  129. async def get_session_token(request: Request) -> Union[str, None]:
  130. return request.session.get("antiAbuseToken")
  131. async def protect_chat_api(
  132. request: Request,
  133. x_app_token: Annotated[Union[str, None], Header(alias="X-App-Token")] = None,
  134. session_token: Annotated[Union[str, None], Depends(get_session_token)] = None
  135. ):
  136. # Equivalent to protectChatAPI middleware
  137. if not session_token:
  138. raise HTTPException(status_code=403, detail="Acceso denegado: Sesión inválida o token no inicializado.")
  139. if not x_app_token:
  140. raise HTTPException(status_code=401, detail="Acceso denegado: Falta el token X-Chat-Token.")
  141. if x_app_token != session_token:
  142. # Log this attempt for security monitoring
  143. print(f"WARN: Invalid token attempt. Expected: {session_token}, Received: {x_app_token}")
  144. raise HTTPException(status_code=403, detail="Acceso denegado: Token inválido.")
  145. return True # Protection passed
  146. @app.get("/api/get_products", summary="Get products")
  147. async def get_products():
  148. return JSONResponse({"products": all_products})
  149. # --- API Endpoints ---
  150. @app.get("/api/chat/init-chat", summary="Initialize chat and get anti-abuse token")
  151. async def init_chat(request: Request):
  152. current_token = request.session.get("antiAbuseToken")
  153. if not current_token:
  154. new_token = secrets.token_hex(32)
  155. request.session["antiAbuseToken"] = new_token # Store in session
  156. print(f"Generated new antiAbuseToken for session: {new_token}")
  157. return JSONResponse({"chatToken": new_token})
  158. else:
  159. # print(f"Using existing antiAbuseToken for session: {current_token}")
  160. return JSONResponse({"chatToken": current_token})
  161. class UserCodeRequest(BaseModel):
  162. user_code: str
  163. @app.post("/api/existsUser", summary="Check if user exists")
  164. async def exists_user(request: UserCodeRequest):
  165. with open('users.json', 'r') as f:
  166. users = json.load(f)
  167. for user in users:
  168. if user['userCode'] == request.user_code:
  169. return JSONResponse({
  170. "success": True,
  171. "userName": user['userName']
  172. })
  173. return JSONResponse({
  174. "success": False,
  175. "userName": None
  176. })
  177. @app.post("/api/printer/order", summary="Printer order", dependencies=[Depends(protect_chat_api)])
  178. async def printer_order(order: OrderWeb):
  179. print("Printer order received")
  180. print(order)
  181. items = order.items
  182. table = order.table
  183. printer = PrinterUSB(0xfe6,0x811e)
  184. print_order = Order(order.customerName,[Item(item.name, item.price, item.quantity) for item in items])
  185. try:
  186. printer.print_order(print_order, table)
  187. except:
  188. return JSONResponse(status_code=424, content={"message": "No se pudo imprimir el Pedido, impresora desconectada"})
  189. if not os.path.exists('logs.csv'):
  190. with open('logs.csv', 'w', newline='') as f:
  191. writer = csv.writer(f)
  192. writer.writerow(['userName', 'table', 'orderDate', 'items'])
  193. with open('logs.csv', 'a', newline='') as f:
  194. writer = csv.writer(f)
  195. writer.writerow([order.customerName, order.table, order.orderDate, items])
  196. @app.post("/api/chat/completions",
  197. summary="Get chat completions from OpenAI",
  198. dependencies=[Depends(protect_chat_api)])
  199. async def chat_completions(request_data: ChatCompletionRequest, request: Request):
  200. # Uses session_token (which is the antiAbuseToken) as an identifier for logging
  201. session_identifier = request.session.get("antiAbuseToken", "unknown_session")
  202. try:
  203. openai_response = await generate_completion(request_data.messages, session_identifier)
  204. return JSONResponse({"response": openai_response})
  205. except HTTPException as e: # Re-raise HTTPExceptions from called functions
  206. raise e
  207. except Exception as e:
  208. print(f"Unexpected error in /api/chat/completions: {e}")
  209. raise HTTPException(status_code=500, detail="Error interno del servidor al procesar el chat.")
  210. @app.get("/", response_class=HTMLResponse, include_in_schema=False)
  211. async def serve_index_html():
  212. index_path = os.path.join("public", "index.html")
  213. if not os.path.exists(index_path):
  214. raise HTTPException(status_code=404, detail="public/index.html not found.")
  215. return FileResponse(index_path)
  216. app.mount("/", StaticFiles(directory="public", html=False), name="public_root_assets")
  217. # --- Main Application Runner ---
  218. if __name__ == "__main__":
  219. if not OPENAI_API_KEY:
  220. print("FATAL: OPENAI_API_KEY is not set. OpenAI features will fail.")
  221. print("Please create a .env file with OPENAI_API_KEY='your_key_here'")
  222. with open(".env", "w") as f:
  223. f.write("OPENAI_API_KEY='your_key_here'")
  224. print(f"Servidor corriendo en http://localhost:{PORT}")
  225. if not os.path.exists(BG_DATA_PATH):
  226. print(f"ADVERTENCIA: {BG_DATA_PATH} no encontrado. El asistente de IA no tendrá datos específicos del menú.")
  227. else:
  228. print(f"Datos del asistente cargados desde: {os.path.abspath(BG_DATA_PATH)}")
  229. import uvicorn
  230. uvicorn.run(app, host="0.0.0.0", port=PORT)