main.py 10 KB

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