hyunjunian commited on
Commit
a8e02b6
·
1 Parent(s): 7262063

update audio and image

Browse files
app.py CHANGED
@@ -1,51 +1,101 @@
1
  import gradio as gr
2
  import requests
3
  from io import BytesIO
 
4
 
5
- def abnormal_stream(image):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
  try:
7
  byte_io = BytesIO()
8
  image.save(byte_io, 'png')
9
  byte_io.seek(0)
10
 
11
  r = requests.post(
12
- 'https://6a051cv20250210-prediction.cognitiveservices.azure.com/customvision/v3.0/Prediction/29f565b7-4710-47a5-8a47-723048ff7ec9/classify/iterations/Iteration2/image',
13
  headers={
14
- 'Prediction-Key': '8uyKSiqRNbG2JLdMjI8AeOzADtORP3jRh5klqQr0JsJrBBt7x7iPJQQJ99BBACYeBjFXJ3w3AAAIACOGHg4K',
15
  'Content-Type': 'application/octet-stream',
16
  },
17
  data=byte_io,
18
  )
19
 
20
  if r.status_code != 200:
21
- return {'확인불가': 1.0, r.status_code: 0.0, r.text: 0.0}, None
22
 
23
- output_dict = {}
 
 
 
 
24
 
25
- for item in r.json()['predictions']:
26
- tag_name = item['tagName']
27
- probability = item['probability']
28
- output_dict[tag_name] = probability
29
 
30
- with open('alert.wav', 'rb') as f:
31
- output_audio = f.read()
32
- return output_dict, output_audio
 
 
 
 
 
 
 
 
 
 
33
 
34
  except Exception as e:
35
- return {str(e): 1.0}
36
 
37
- with gr.Blocks(
38
- analytics_enabled=False,
39
- title='졸음운전 알리미',
40
- head='''<meta name="theme-color" content="#0f0f11">''',
41
- ) as demo:
42
  with gr.Row():
43
  with gr.Column():
44
  input_img = gr.Image(sources=["webcam"], type="pil")
45
  with gr.Column():
46
- output_label = gr.Label()
47
- output_audio = gr.Audio(autoplay=True)
48
- dep = input_img.stream(abnormal_stream, [input_img], [output_label, output_audio])
 
 
49
 
50
  if __name__ == "__main__":
51
- demo.launch(favicon_path='./favicon.png', show_api=False)
 
1
  import gradio as gr
2
  import requests
3
  from io import BytesIO
4
+ import random
5
 
6
+ # 행동별 KSS 점수 설정 (제곱 값 적용)
7
+ kss_mapping = {
8
+ "운전하다": 1,
9
+ "눈비비기": 21,
10
+ "어깨를두드리다": 25,
11
+ "목을만지다": 25,
12
+ "하품": 36,
13
+ "뺨을때리다": 64,
14
+ "꾸벅꾸벅졸다": 81,
15
+ "몸못가누기": 100,
16
+ }
17
+
18
+ risk_images = {
19
+ "매우 안전": "image1.png",
20
+ "안전": "image2.png",
21
+ "주의": "image3.png",
22
+ "위험": "image4.png",
23
+ "매우 위험": "image5.png",
24
+ }
25
+
26
+ def get_risk_status(avg_kss, slope):
27
+ """
28
+ 윈도우 내 평균 KSS에 따라 5단계 위험 상태를 반환.
29
+ """
30
+ if avg_kss < 9:
31
+ return "매우 안전", "image1.png", None
32
+ elif avg_kss < 20:
33
+ return "안전", "image2.png", None
34
+ elif avg_kss < 40:
35
+ return "주의", "image3.png", "약간 피로해보여요.잠시 쉬었다 가시는걸 추천드려요.mp3"
36
+ elif avg_kss < 75:
37
+ return "위험", "image4.png", random.choice([
38
+ "졸음이 온다면 차라리 관속에 누우세요.mp3",
39
+ "미치셨습니까 휴먼.mp3",
40
+ "지금자면 병원에서 깨실걸요 ㅋㅋ.mp3"
41
+ ])
42
+ else:
43
+ return "매우 위험", "image5.png", "사이렌.mp3"
44
+
45
+ def analyze_frame(image):
46
  try:
47
  byte_io = BytesIO()
48
  image.save(byte_io, 'png')
49
  byte_io.seek(0)
50
 
51
  r = requests.post(
52
+ 'https://6b003cv20250210-prediction.cognitiveservices.azure.com/customvision/v3.0/Prediction/03fa2862-cb54-4344-b484-630379edffaa/classify/iterations/Iteration4/image',
53
  headers={
54
+ 'Prediction-Key': '8ypy2B3ZECnRG0PaYKzpSNvOz8yAhfF7MY2z2wQxSzkweNlhgI4SJQQJ99BBACYeBjFXJ3w3AAAIACOG0WmE',
55
  'Content-Type': 'application/octet-stream',
56
  },
57
  data=byte_io,
58
  )
59
 
60
  if r.status_code != 200:
61
+ return "결과 없음", "image1.png", None
62
 
63
+ top_predictions_3 = sorted(r.json()['predictions'], key=lambda x: x['probability'], reverse=True)[:3]
64
+ top_prediction_1 = top_predictions_3[0]
65
+ action_name = top_prediction_1['tagName']
66
+ kss_score = kss_mapping.get(action_name, 0)
67
+ avg_kss = kss_score
68
 
69
+ # 위험 상태 및 이미지/음성 정보 가져오기
70
+ risk_state, risk_image, audio_file = get_risk_status(avg_kss, None)
 
 
71
 
72
+ results_text = f"🎬 실시간 행동 분석\n\n"
73
+ for prediction in top_predictions_3:
74
+ results_text += f"{prediction['tagName']}: {prediction['probability'] * 100:.2f}%\n"
75
+ results_text += f"🔹 가장 유사한 행동: {action_name} | KSS 점수: {kss_score}\n"
76
+ results_text += f"📊 현재 위험 수준: {risk_state}\n"
77
+
78
+ # 자동 재생을 위한 Audio 컴포넌트
79
+ if audio_file:
80
+ audio_output = gr.Audio(value=audio_file, autoplay=True)
81
+ else:
82
+ audio_output = None
83
+
84
+ return results_text, risk_image, audio_output
85
 
86
  except Exception as e:
87
+ return f"오류 발생: {str(e)}", "image1.png", None
88
 
89
+ with gr.Blocks() as demo:
 
 
 
 
90
  with gr.Row():
91
  with gr.Column():
92
  input_img = gr.Image(sources=["webcam"], type="pil")
93
  with gr.Column():
94
+ output_label = gr.Textbox(label="🔍 분석 결과")
95
+ output_image = gr.Image(label="📊 위험 수준", height=200, width=200)
96
+ output_audio = gr.Audio(label="🔊 음성 경고")
97
+
98
+ input_img.stream(analyze_frame, [input_img], [output_label, output_image, output_audio])
99
 
100
  if __name__ == "__main__":
101
+ demo.launch(debug=True)
app2.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import requests
3
+ from io import BytesIO
4
+
5
+ def abnormal_stream(image):
6
+ try:
7
+ byte_io = BytesIO()
8
+ image.save(byte_io, 'png')
9
+ byte_io.seek(0)
10
+
11
+ r = requests.post(
12
+ 'https://6a051cv20250210-prediction.cognitiveservices.azure.com/customvision/v3.0/Prediction/29f565b7-4710-47a5-8a47-723048ff7ec9/classify/iterations/Iteration2/image',
13
+ headers={
14
+ 'Prediction-Key': '8uyKSiqRNbG2JLdMjI8AeOzADtORP3jRh5klqQr0JsJrBBt7x7iPJQQJ99BBACYeBjFXJ3w3AAAIACOGHg4K',
15
+ 'Content-Type': 'application/octet-stream',
16
+ },
17
+ data=byte_io,
18
+ )
19
+
20
+ if r.status_code != 200:
21
+ return {'확인불가': 1.0, r.status_code: 0.0, r.text: 0.0}, None
22
+
23
+ output_dict = {}
24
+
25
+ for item in r.json()['predictions']:
26
+ tag_name = item['tagName']
27
+ probability = item['probability']
28
+ output_dict[tag_name] = probability
29
+
30
+ with open('alert.wav', 'rb') as f:
31
+ output_audio = f.read()
32
+ return output_dict, output_audio
33
+
34
+ except Exception as e:
35
+ return {str(e): 1.0}
36
+
37
+ with gr.Blocks(
38
+ analytics_enabled=False,
39
+ title='졸음운전 알리미',
40
+ head='''<meta name="theme-color" content="#0f0f11">''',
41
+ ) as demo:
42
+ with gr.Row():
43
+ with gr.Column():
44
+ input_img = gr.Image(sources=["webcam"], type="pil")
45
+ with gr.Column():
46
+ output_label = gr.Label()
47
+ output_audio = gr.Audio(autoplay=True)
48
+ dep = input_img.stream(abnormal_stream, [input_img], [output_label, output_audio])
49
+
50
+ if __name__ == "__main__":
51
+ demo.launch(favicon_path='./favicon.png', show_api=False)
image1.png ADDED
image2.png ADDED
image3.png ADDED
image4.png ADDED
image5.png ADDED
음성/주의/눈이 무거워지고 있어요. 한 번 크게 기지개를 켜보세요.mp3 → 눈이 무거워지고 있어요. 한 번 크게 기지개를 켜보세요.mp3 RENAMED
File without changes
음성/주의/많이 피곤해보이시네요. 신나는 음악 한 곡 어떠세요.mp3 → 많이 피곤해보이시네요. 신나는 음악 한 곡 어떠세요.mp3 RENAMED
File without changes
음성/위험/미치셨습니까 휴먼.mp3 → 미치셨습니까 휴먼.mp3 RENAMED
File without changes
음성/매우위험/사이렌.mp3 → 사이렌.mp3 RENAMED
File without changes
음성/주의/약간 피로해보여요.잠시 쉬었다 가시는걸 추천드려요.mp3 → 약간 피로해보여요.잠시 쉬었다 가시는걸 추천드려요.mp3 RENAMED
File without changes
음성/위험/졸음이 온다면 차라리 관속에 누우세요.mp3 → 졸음이 온다면 차라리 관속에 누우세요.mp3 RENAMED
File without changes
음성/위험/지금자면 병원에서 깨실걸요 ㅋㅋ.mp3 → 지금자면 병원에서 깨실걸요 ㅋㅋ.mp3 RENAMED
File without changes