-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
323 lines (263 loc) · 9.98 KB
/
app.py
File metadata and controls
323 lines (263 loc) · 9.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
import os
import httpx
import openai
from fastapi import FastAPI, HTTPException, Request
from pydantic import BaseModel, Field
from text.sentiment_analysis import classify_emotion, generate_chat_response, load_models_and_data
from text.text_preprocessing import has_command
from fastapi.responses import FileResponse
import rclpy
from rclpy.node import Node
from std_msgs.msg import String
import threading
import subprocess
from pathlib import Path
import json
import signal
import time
import firebase_admin
from firebase_admin import messaging, credentials
from typing import Union
# FastAPI 앱 객체 생성
app = FastAPI(
title="Hear-Bear ChatGPT API",
description="프론트엔드에서 온 문장을 감정 분류 후 ChatGPT에 전달하여 답변을 반환하는 API",
version="1.0"
)
# 요청(Request) 및 응답(Response) 모델 정의
class ChatRequest(BaseModel):
message: str = Field(description="프론트엔드로부터 전달받은 새로운 사용자 메시지")
class CommandResponse(BaseModel):
command: str = Field(description="예약어가 감지될 시, /get-command로 해당 예약어의 행동을 실행하게끔 하는 response dto")
class ChatResponse(BaseModel):
sentiment: str = Field(..., description="분류된 감정 레이블(예: '행복', '슬픔', '분노' 등)")
confidence: float = Field(..., description="분류 확률 또는 SBERT-KNN fallback 신뢰도")
bot_reply: str = Field(..., description="ChatGPT가 반환한 답변 메시지")
# history: List[str] = Field(description="응답 후 업데이트된 대화 내역(추가된 사용자 메시지와 봇의 답변 포함)", default_factory=list)
# OpenAI의 일반적인 Example response
# [
# {
# "index": 0,
# "message": {
# "role": "assistant",
# "content": "Under the soft glow of the moon, Luna the unicorn danced through fields of twinkling stardust, leaving trails of dreams for every child asleep.",
# "refusal": null
# },
# "logprobs": null,
# "finish_reason": "stop"
# }
# ]
# 이 중에서, chat에 필요한 데이터는 index, content
@app.on_event("startup")
async def on_startup():
"""
서버가 시작될 때 단 한 번만 실행됩니다.
여기서 무거운 모델 로드 및 데이터 로드를 수행합니다.
"""
print(">> 서버 시작 시, 감정 분류 모델과 SBERT 임베딩을 한 번만 로드합니다.")
load_models_and_data()
print(">> 모델 로드 완료!!")
global ros_node
rclpy.init()
ros_node = RosPublisherNode()
threading.Thread(target=ros_spin_thread, args=(ros_node,), daemon=True).start()
@app.get("/ping")
async def ping():
return {"pong": True}
# POST /chat 엔드포인트 정의
@app.post("/chat", response_model=Union[ChatResponse, CommandResponse])
async def chat_endpoint(request: ChatRequest):
"""
1) request.message → classify_emotion 으로 감정 분류
2) 분류 결과(sentiment, confidence)와 request.history (이전 대화들) 을
generate_chat_response 에 전달 → ChatGPT 답변 받기
3) 최종 JSON 형태로 응답
"""
FIXED_TFIDF_THRESHOLD = 0.75
print(request.message)
# 예약어 여부 검사
cmd_detected, matched_sentence = has_command(request.message)
if cmd_detected:
# 예약어가 감지되면 동일 IP에 POST /get-command 요청
try:
# http://localhost:8000/get-command 으로 예약어 전송
async with httpx.AsyncClient() as client:
resp = await client.post(
"http://192.168.0.17:8000/get-command",
json={"command": matched_sentence},
timeout=5.0
)
resp.raise_for_status()
print(f"[HTTP POST] /get-command → payload: {{'command': '{matched_sentence}'}}")
except Exception as e:
print(f"[ERROR] /get-command 호출 실패: {e}")
# 예약어 처리 후 바로 응답 (감정 분류 & ChatGPT 호출 건너뛰기)
return CommandResponse(
command=matched_sentence,
)
# 1) 감정 분류
try:
cls_res = classify_emotion(request.message, tfidf_threshold=FIXED_TFIDF_THRESHOLD)
except Exception as e:
raise HTTPException(status_code=500, detail=f"감정 분류 중 오류 발생: {str(e)}")
sentiment = cls_res["sentiment"]
confidence = cls_res["confidence"]
# 2) ChatGPT 응답 생성
try:
bot_reply = generate_chat_response(request.message, sentiment)
except Exception as e:
raise HTTPException(status_code=500, detail=f"ChatGPT 호출 중 오류 발생: {str(e)}")
# 3) 봇의 답변을 내역에 추가
# new_history.append(bot_reply)
return ChatResponse(
sentiment=sentiment,
confidence=confidence,
bot_reply=bot_reply
)
# ROS 노드 정의
class RosPublisherNode(Node):
def __init__(self):
super().__init__('fastapi_ros_node')
self.command_publisher = self.create_publisher(String, 'command', 10)
self.pixel_goal_publisher = self.create_publisher(String, 'pixel_goal', 10)
self.reexplore_publisher = self.create_publisher(String, 'reexplore', 10)
def publish_command(self, text):
msg = String()
msg.data = text
self.command_publisher.publish(msg)
self.get_logger().info(f"Published command: {text}")
def publish_pixel_goal(self, px, py):
msg = String()
msg.data = f"{px},{py}"
self.pixel_goal_publisher.publish(msg)
self.get_logger().info(f"Published pixel goal: {px},{py}")
def publish_reexplore(self):
msg = String()
self.reexplore_publisher.publish(msg)
self.get_logger().info(f"Published reexplore")
class NoiseCoordinate(BaseModel):
name: str
x: float
y: float
# ROS 노드 전역 인스턴스 생성
ros_node = None
def ros_spin_thread(node):
try:
rclpy.spin(node)
except rclpy.executors.ExternalShutdownException:
print("[ROS] rclpy shutdown 감지 → spin 종료됨")
"""
@app.on_event("startup")
def startup_event():
global ros_node
rclpy.init()
ros_node = RosPublisherNode()
threading.Thread(target=ros_spin_thread, args=(ros_node,), daemon=True).start()
"""
@app.on_event("shutdown")
def shutdown_event():
global ros_node
ros_node.destroy_node()
rclpy.shutdown()
@app.get("/")
def hello():
return {"message": "Hello world"}
listener_proc = None # 전역 listener 프로세스 참조
@app.post("/get-command")
async def receive_test(request: Request):
global listener_proc
# 1) JSON 파싱
try:
data = await request.json()
command = data.get("command")
if not command:
raise ValueError("`command` 필드가 없습니다.")
except Exception as e:
raise HTTPException(status_code=400, detail=str(e))
print(f"[FastAPI] 받은 명령어: {command}")
# subprocess.Popen(["ros2", "run", "hearbear", "command_listener.py"])
# 4) Listener가 spin 시작할 시간을 잠깐 줌
time.sleep(0.5)
# 5) 퍼블리시
ros_node.publish_command(command)
return {"status": "ok", "command": command}
def launch_ros2_mapping():
subprocess.Popen(["ros2", "launch", "hearbear", "cartographer_mapping.launch.py"])
@app.get("/get-map")
def get_map():
image_path = "/home/nvidia/turtlebot3_ws/map/map.png"
if os.path.exists(image_path):
return FileResponse(image_path, media_type="image/png")
else:
return {"error": "Image not found"}
@app.post('/pixel-to-navi')
async def navigate(payload: dict):
try:
px = int(payload.get('px'))
py = int(payload.get('py'))
except (ValueError, TypeError):
return {"error": "Invalid 'px' or 'py' in payload. Must be integers."}
ros_node.publish_pixel_goal(px, py)
return {'status': 'pixel goal sent', 'px': px, 'py': py}
@app.post("/request_reexplore")
async def request_reexplore():
ros_node.publish_reexplore()
return {"status": "재탐색 요청이 전달되었습니다."}
class DestinationItem(BaseModel):
category: str
px: float
py: float
DEST_PATH = Path("/home/nvidia/turtlebot3_ws/dest_list/destination.json")
@app.post("/save-destination")
async def save_destination(destinations: list[DestinationItem]):
try:
# 상위 디렉토리 생성
DEST_PATH.parent.mkdir(parents=True, exist_ok=True)
# 리스트를 dict로 변환 후 저장
data_to_save = [dest.dict() for dest in destinations]
with open(DEST_PATH, "w", encoding="utf-8") as f:
json.dump(data_to_save, f, ensure_ascii=False, indent=2)
except Exception as e:
return {"error": f"File write failed: {str(e)}"}
return {
"message": "Destination saved successfully",
"path": str(DEST_PATH),
"count": len(destinations)
}
tokens = []
cred = credentials.Certificate("serviceAccountKey.json")
firebase_admin.initialize_app(cred)
class TokenModel(BaseModel):
token: str
@app.post("/register_token")
def register_token(data: TokenModel):
tokens.append(data.token)
print("등록된 토큰: ", data.token)
return {"status":"received"}
def send_notification():
message = messaging.Message(
notification=messaging.Notification(
title="알림 제목",
body="알림 내용"
),
token="사용자_FCM_토큰"
)
response = messaging.send(message)
print("푸시 전송 성공:", response)
class PushRequest(BaseModel):
title: str
body: str
@app.post("/send_push")
def send_push(data: PushRequest):
if not tokens:
return {"error": "No token registered yet"}
message = messaging.Message(
notification=messaging.Notification(
title=data.title,
body=data.body
),
token=tokens[-1]
)
response = messaging.send(message)
print("푸시 전송 성공:", response)
return {"status": "success", "response": response}