|
| 1 | +package com.ureca.unity.domain.stt.service; |
| 2 | + |
| 3 | +import com.google.cloud.speech.v1.*; |
| 4 | +import com.google.protobuf.ByteString; |
| 5 | +import com.ureca.unity.domain.stt.mapper.SttMapper; |
| 6 | +import com.ureca.unity.domain.stt.model.SttJob; |
| 7 | +import lombok.RequiredArgsConstructor; |
| 8 | +import org.springframework.stereotype.Service; |
| 9 | + |
| 10 | +import java.nio.file.Files; |
| 11 | +import java.nio.file.Paths; |
| 12 | +import java.util.stream.Collectors; |
| 13 | + |
| 14 | +@Service |
| 15 | +@RequiredArgsConstructor |
| 16 | +public class SttServiceImpl implements SttService { |
| 17 | + |
| 18 | + private final SttMapper sttMapper; |
| 19 | + |
| 20 | + @Override |
| 21 | + public SttJob startStt(Long counselingId) { |
| 22 | + |
| 23 | + Long userId = 1L; // 임시 |
| 24 | + |
| 25 | + SttJob job = sttMapper.findByCounselingId(counselingId); |
| 26 | + |
| 27 | + if (job == null) { |
| 28 | + job = SttJob.builder() |
| 29 | + .counselingId(counselingId) |
| 30 | + .userId(userId) |
| 31 | + .summaryType("CALL") |
| 32 | + .status("LOADING") |
| 33 | + .build(); |
| 34 | + sttMapper.insert(job); |
| 35 | + } |
| 36 | + |
| 37 | + try { |
| 38 | + |
| 39 | + String audioPath = "C:/Users/bagju/Desktop/realsample.wav"; |
| 40 | + |
| 41 | + byte[] data = Files.readAllBytes(Paths.get(audioPath)); |
| 42 | + ByteString audioBytes = ByteString.copyFrom(data); |
| 43 | + |
| 44 | + RecognitionAudio audio = RecognitionAudio.newBuilder() |
| 45 | + .setContent(audioBytes) |
| 46 | + .build(); |
| 47 | + |
| 48 | + |
| 49 | + RecognitionConfig config = RecognitionConfig.newBuilder() |
| 50 | + .setEncoding(RecognitionConfig.AudioEncoding.LINEAR16) |
| 51 | + .setLanguageCode("ko-KR") |
| 52 | + .setAudioChannelCount(2) // stereo |
| 53 | + .setEnableSeparateRecognitionPerChannel(true) // 채널 분리 |
| 54 | + // sampleRateHertz는 WAV 헤더 기준 → 명시 안 함 |
| 55 | + .build(); |
| 56 | + |
| 57 | + try (SpeechClient speechClient = SpeechClient.create()) { |
| 58 | + |
| 59 | + RecognizeResponse response = |
| 60 | + speechClient.recognize(config, audio); |
| 61 | + |
| 62 | + // 채널 상관없이 전부 합침 (지금은 검증 목적) |
| 63 | + String text = response.getResultsList().stream() |
| 64 | + .map(r -> r.getAlternatives(0).getTranscript()) |
| 65 | + .collect(Collectors.joining(" ")); |
| 66 | + |
| 67 | + job.setStatus("SUCCESS"); |
| 68 | + job.setSummaryText(text); |
| 69 | + } |
| 70 | + |
| 71 | + } catch (Exception e) { |
| 72 | + e.printStackTrace(); |
| 73 | + job.setStatus("FAIL"); |
| 74 | + job.setSummaryText(null); |
| 75 | + } |
| 76 | + |
| 77 | + sttMapper.updateResult(job); |
| 78 | + return job; |
| 79 | + } |
| 80 | + |
| 81 | + @Override |
| 82 | + public SttJob getStt(Long counselingId) { |
| 83 | + return sttMapper.findByCounselingId(counselingId); |
| 84 | + } |
| 85 | +} |
0 commit comments