main.py 10 KB

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