context.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. from __future__ import annotations
  2. from sqlalchemy.orm import Session
  3. from app.db.repositories import diagnosis as diagnosis_repo
  4. from app.db.repositories import document as document_repo
  5. from app.db.repositories import evaluation as evaluation_repo
  6. from app.db.repositories import knowledge as knowledge_repo
  7. from app.db.repositories import monitoring as monitoring_repo
  8. from app.db.repositories import work_order as work_order_repo
  9. from app.services.mine_service import resolve_mine
  10. def build_mine_context(
  11. db: Session,
  12. mine_id: str | None,
  13. *,
  14. include_documents: bool = False,
  15. ) -> dict:
  16. mine = resolve_mine(db, mine_id)
  17. context = {
  18. "mine": {
  19. "id": mine.id,
  20. "code": mine.code,
  21. "name": mine.name,
  22. "ventilation_method": mine.ventilation_method,
  23. },
  24. "monitoring": monitoring_repo.monitoring_overview(db, mine.id),
  25. "diagnosis": diagnosis_repo.result_summary(db, mine.id),
  26. "work_orders": work_order_repo.status_summary(db, mine.id),
  27. }
  28. runs = evaluation_repo.list_runs(db, mine.id, limit=1)
  29. if runs:
  30. context["latest_evaluation"] = {
  31. "run_no": runs[0].run_no,
  32. "score": runs[0].total_score,
  33. "grade": runs[0].grade,
  34. "summary": runs[0].summary,
  35. }
  36. if include_documents:
  37. documents, total = document_repo.list_documents(
  38. db,
  39. mine_id=mine.id,
  40. page=1,
  41. page_size=10,
  42. )
  43. context["documents"] = {
  44. "total": total,
  45. "recent": [
  46. {
  47. "id": item.id,
  48. "title": item.title,
  49. "category": item.category,
  50. "parse_status": item.parse_status,
  51. }
  52. for item in documents
  53. ],
  54. }
  55. return context
  56. def build_knowledge_context(
  57. db: Session,
  58. mine_id: str | None,
  59. question: str,
  60. limit: int = 8,
  61. ) -> dict:
  62. items, total = knowledge_repo.list_knowledge(
  63. db,
  64. mine_id=mine_id,
  65. keyword=question,
  66. page=1,
  67. page_size=limit,
  68. )
  69. return {
  70. "total": total,
  71. "items": [
  72. {
  73. "id": item.id,
  74. "code": item.code,
  75. "title": item.title,
  76. "type": item.knowledge_type,
  77. "category": item.category,
  78. "summary": item.summary,
  79. "content": item.content[:1200],
  80. }
  81. for item in items
  82. ],
  83. }