main.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. from fastapi import FastAPI, Form, UploadFile, File, HTTPException
  2. import uvicorn
  3. from fastapi.middleware.cors import CORSMiddleware
  4. from fastapi.middleware.httpsredirect import HTTPSRedirectMiddleware
  5. from fastapi.middleware.trustedhost import TrustedHostMiddleware
  6. from datetime import datetime
  7. from fastapi.staticfiles import StaticFiles
  8. from datetime import datetime
  9. from fastapi.responses import RedirectResponse
  10. import logging
  11. from logging.handlers import TimedRotatingFileHandler
  12. # 設定日誌配置
  13. log_folder = 'log'
  14. log_file = f'{log_folder}/app.log'
  15. # 設定日誌格式
  16. log_format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
  17. date_format = '%Y-%m-%d %H:%M:%S'
  18. # 設定 TimedRotatingFileHandler
  19. handler = TimedRotatingFileHandler(
  20. log_file,
  21. when='midnight',
  22. interval=1,
  23. backupCount=7 # 保留7天的日誌
  24. )
  25. handler.setFormatter(logging.Formatter(log_format, datefmt=date_format))
  26. # 設定根日誌
  27. logging.basicConfig(
  28. handlers=[handler],
  29. level=logging.INFO,
  30. format=log_format,
  31. datefmt=date_format
  32. )
  33. console_handler = logging.StreamHandler()
  34. app = FastAPI()
  35. # app.add_middleware(HTTPSRedirectMiddleware)
  36. # app.add_middleware(TrustedHostMiddleware)
  37. app.add_middleware(
  38. CORSMiddleware,
  39. allow_origins=["*"],
  40. allow_credentials=True,
  41. allow_methods=["*"],
  42. allow_headers=["*"],
  43. )
  44. app.mount("/static", StaticFiles(directory="static"), name="static")
  45. # 根目錄導向docs
  46. @app.get("/")
  47. async def root():
  48. logging.info("Root endpoint was called")
  49. return RedirectResponse(url="/docs#")
  50. from api.tts_router import ttsRouter
  51. from api.db_router import dbRouter
  52. from api.tendent_router import tendentRouter
  53. # from api.speech2text import router
  54. # from api.tts_try import ttsTryRouter
  55. app.include_router(ttsRouter, prefix="", tags=["文字轉語音"])
  56. app.include_router(dbRouter, prefix="", tags=["supa 操作相關"])
  57. app.include_router(tendentRouter, prefix="", tags=["天燈"])
  58. # app.include_router(router, prefix='/speech2text', tags=["speech2text"])
  59. # app.include_router(ttsTryRouter, prefix='/ttsTry', tags=["測試本地端tts"])
  60. @app.get("/ad")
  61. def read_root(language :str = "ch"):
  62. message = {}
  63. if language == "ch" :
  64. message = {
  65. "type": "store",
  66. "body": {
  67. "cover_img": "https://cmm.ai:9101/static/ad_img/ad-img.png",
  68. "title": "台北101國際貴賓卡",
  69. "description":"國際貴賓卡專屬禮遇\n●即日起來台北101,提供2024年特別禮遇-申辦台北101國際貴賓卡,可享用國際旅客限定專屬三重好禮:\n●購物-品牌9折起特別優惠\n●禮遇-Welcome Pack+ NTD300現金折抵券\n●退稅-消費2000元以上提供5%快速退稅服務\n<a href='https://stage.taipei101mall.com.tw/join-member/AIsystem' class='ar-link mt-3' target='_blank'>立即申辦</a>",
  70. "date": "即日起",
  71. "price": "",
  72. "original_price": "",
  73. "website_url": "",
  74. "store_info_url": "",
  75. "included": [],
  76. "branch": [],
  77. "location" : ""
  78. },
  79. }
  80. else :
  81. message = {
  82. "type": "store",
  83. "body": {
  84. "cover_img": "https://cmm.ai:9101/static/ad_img/ad-img.png",
  85. "title": "Taipei 101 International VIP Card",
  86. "description":"TOURIST CARD Exclusive Privileges\nStarting today at Taipei 101, we are offering special privileges for the year 2024 - apply for the Taipei 101 Tourist Card and enjoy exclusive triple benefits reserved for international travelers.\n● Shopping - Special offers starting from 10% off brand items.\n● PRIVILEGES-Welcome Pack + NTD300 cash voucher.\n● TAX REFUND- Offering 5% expedited processing service.\n<a href='https://stage.taipei101mall.com.tw/join-member/AIsystem' class='ar-link mt-3' target='_blank'>Apply now</a>",
  87. "date": "Starting from today",
  88. "price": "",
  89. "original_price": "",
  90. "website_url": "",
  91. "store_info_url": "",
  92. "included": [],
  93. "branch": [],
  94. "location" : ""
  95. },
  96. }
  97. return {"data": message}
  98. from api.image_operate import remove_background,detect_face
  99. @app.post("/image_check")
  100. async def image_check(image_file : UploadFile):
  101. currentDateAndTime = datetime.now()
  102. imgname = currentDateAndTime.strftime("%m-%d-%H-%M-%S")+ "-" + image_file.filename
  103. with open(f"/home/mia/101/static/image/{imgname}","wb") as save_img :
  104. contents = await image_file.read()
  105. save_img.write(contents)
  106. # await remove_background(f"/home/mia/101/static/image/{imgname}",f"/home/mia/101/static/image/remove/{imgname}")
  107. result = await detect_face(f"/home/mia/101/static/image/{imgname}")
  108. return result
  109. if __name__ == "__main__":
  110. uvicorn.run("main:app", host="0.0.0.0", port=9101, reload=False, log_config=None)