-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.js
More file actions
334 lines (299 loc) · 9.54 KB
/
App.js
File metadata and controls
334 lines (299 loc) · 9.54 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
323
324
325
326
327
328
329
330
331
332
333
334
// import { AppRegistry } from "react-native";
// AppRegistry.registerComponent(appName, () => App());
import React, { useState, useEffect } from "react";
import {
StyleSheet,
View,
TouchableOpacity,
Text,
Alert,
Platform,
} from "react-native";
import Slider from "@react-native-community/slider";
import * as FileSystem from "expo-file-system";
import * as Permissions from "expo-permissions";
import * as Sharing from "expo-sharing";
import { Audio } from "expo-av";
import axios from "axios";
import { NativeModules } from "react-native";
//import { manipulateAsync } from 'expo-image-manipulator';
import OpenAI from "openai";
import { API_KEY, Google_API_KEY, IP_ADDRESS } from "./config";
// import { RNFFmpeg } from 'react-native-ffmpeg';
//const fs = require('fs');
//const filePath = '/Users/kabir/AudioNote/transcription-server/transcriptionFile(s)/transcription.txt';
const openai = new OpenAI({
apiKey: API_KEY,
});
export default function App() {
const [recording, setRecording] = useState(null);
const [sound, setSound] = useState(null);
const [progress, setProgress] = useState(0);
const [gainValue, setGainValue] = useState(1);
const [uri, setUri] = useState("");
const [generatedResponse, setGeneratedResponse] = useState("");
const [transcription, setTranscription] = useState("");
const [fileData, setFileData] = useState("");
const [userMessage, setUserMessage] = useState("");
const [chatHistory, setChatHistory] = useState([]);
useEffect(() => {
getPermissions();
fetchTranscription();
}, []);
const getPermissions = async () => {
const { status: micStatus } = await Permissions.askAsync(Permissions.AUDIO_RECORDING);
const { status:storageStatus} = await Permissions.askAsync(Permissions.MEDIA_LIBRARY);
if (micStatus !== "granted" || storageStatus !== "granted") {
Alert.alert(
"Permissions Denied",
"This app requires microphone and storage permissions to function correctly.",
[{ text: "OK" }]
);
}
};
// const audioAmplify = async (inputFilePath, outputFilePath, amplificationFactor) => {
// try {
// const ffmpegCommand = `-i ${inputFilePath} -filter:a "volume=${amplificationFactor}" ${outputFilePath}`;
// const { rc } = await RNFFmpeg.execute(ffmpegCommand);
// if (rc === 0) {
// console.log("Audio amplified successfully");
// } else {
// console.error("Failed to amplify audio");
// }
// } catch (error) {
// console.error("Error amplifying audio:", error);
// }
// }
const fetchTranscription = async () => {
try {
const response = await axios.get(`http://${IP_ADDRESS}:3000/file`);
setFileData(response.data);
} catch (error) {
console.error("Error fetching transcription:", error);
Alert.alert(
"Fetch Failed",
"An error occurred while trying to fetch the transcription."
);
}
};
async function startRecording() {
try {
await Audio.requestPermissionsAsync();
await Audio.setAudioModeAsync({
allowsRecordingIOS: true,
playsInSilentModeIOS: true,
});
const recordingOptions = {
android: {
extension: ".m4a",
outputFormat: Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_MPEG_4,
audioEncoder: Audio.RECORDING_OPTION_ANDROID_AUDIO_ENCODER_AAC,
sampleRate: 44100,
numberOfChannels: 2,
bitRate: 128000,
},
ios: {
extension: ".wav",
audioQuality: Audio.RECORDING_OPTION_IOS_AUDIO_QUALITY_HIGH,
sampleRate: 44100,
numberOfChannels: 1,
bitRate: 128000,
linearPCMBitDepth: 16,
linearPCMIsBigEndian: false,
linearPCMIsFloat: false,
},
};
const { recording } = await Audio.Recording.createAsync(
recordingOptions,
(status) => setProgress(status.durationMillis / 1000)
);
recording.setProgressUpdateInterval(100);
recording.setOnRecordingStatusUpdate((status) => {
setProgress(status.durationMillis / 1000);
});
setRecording(recording);
} catch (err) {
console.error("Failed to start recording", err);
}
}
async function stopRecording() {
try {
await recording.stopAndUnloadAsync();
const uri = recording.getURI();
console.log("Recording stopped and stored at", uri);
setUri(uri);
console.log("Transcribing audio...");
const formData = new FormData();
formData.append("audio", {
uri,
type: Platform.OS === "ios" ? "audio/x-caf" : "audio/mp4",
name: Platform.OS === "ios" ? "recording.caf" : "recording.m4a",
});
const response = await axios.post(
`http://${IP_ADDRESS}:3000/transcribe`,
formData,
{
headers: {
"Content-Type": "multipart/form-data",
},
}
);
const transcription = response.data.transcription;
console.log("Transcription:", transcription);
//setGeneratedResponse(transcription);
console.log("Audio transcription complete.");
generateResponse(transcription);
fetchTranscription();
setRecording(null);
setProgress(0);
} catch (err) {
console.error("Failed to stop recording", err);
}
}
async function playRecording() {
try {
if (uri) {
console.log("Loading sound from", uri);
const { sound } = await Audio.Sound.createAsync({ uri });
setSound(sound);
console.log("Playing sound...");
await sound.playAsync();
} else {
console.log("No URI set for the recording.");
}
} catch (err) {
console.error("Failed to play recording", err);
}
}
async function shareRecording() {
try {
if (uri) {
await Sharing.shareAsync(uri);
} else {
Alert.alert(
"No Recording",
"There is no recording available to share."
);
}
} catch (err) {
console.error("Failed to share recording", err);
Alert.alert(
"Share Failed",
"An error occurred while trying to share the recording."
);
}
}
const handleResetFile = async () => {
try {
await axios.post(`http://${IP_ADDRESS}:3000/resetTranscriptionFile`);
alert("Previous recording deleted.");
setFileData("");
setGeneratedResponse("");
} catch (error) {
console.error("Error resetting transcription file:", error);
alert("Error resetting transcription file. Please try again.");
}
};
const generateResponse = async (Transcription) => {
try {
const response = await openai.chat.completions.create({
model: "gpt-3.5-turbo",
messages: [{ role: "user", content: fileData + Transcription}],
});
console.log("Generated response:", response.choices[0].message.content);
setGeneratedResponse(response.choices[0].message.content);
} catch (error) {
console.error("Failed to generate response:", error);
Alert.alert(
"Response Generation Failed",
"An error occurred while trying to generate the response."
);
}
};
useEffect(() => {
if (recording) {
Audio.setAudioModeAsync({
allowsRecordingIOS: true,
playsInSilentModeIOS: true,
shouldActivateAudio: true,
interruptionModeIOS: Audio.INTERRUPTION_MODE_IOS_MIX_WITH_OTHERS,
interruptionModeAndroid: Audio.INTERRUPTION_MODE_ANDROID_DUCK_OTHERS,
playThroughEarpieceAndroid: false,
staysActiveInBackground: true,
});
}
return sound
? () => {
console.log("Unloading sound...");
sound.unloadAsync();
}
: undefined;
}, [recording, sound]);
return (
<View style={styles.container}>
<View style={styles.recorder}>
<TouchableOpacity
style={styles.button}
onPress={recording ? stopRecording : startRecording}
>
<Text>{recording ? "Stop Recording" : "Start Recording"}</Text>
</TouchableOpacity>
<Text>Recording Progress: {progress.toFixed(2)} s</Text>
{uri ? (
<>
<TouchableOpacity style={styles.button} onPress={playRecording}>
<Text>Play Recording</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.button} onPress={shareRecording}>
<Text>Share Recording</Text>
</TouchableOpacity>
</>
) : null}
</View>
<View style={styles.responseContainer}>
<Text>Generated Response:</Text>
<Text>{generatedResponse}</Text>
</View>
{/* <View style={styles.gain}>
<Text>Mic Gain</Text>
<Slider
style={{ width: 200, height: 40 }}
minimumValue={0}
maximumValue={10}
value={gainValue}
onValueChange={(value) => setGainValue(value)}
step={0.1}
/>
<Text>{gainValue.toFixed(1)}</Text>
</View> */}
<TouchableOpacity style = {styles.button} onPress={handleResetFile}>
<Text>Reset</Text>
</TouchableOpacity>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
alignItems: "center",
justifyContent: "center",
},
recorder: {
marginBottom: 20,
},
responseContainer: {
marginVertical: 20,
alignItems: "center",
},
button: {
backgroundColor: "#ccc",
padding: 10,
borderRadius: 5,
marginVertical: 5,
},
gain: {
flexDirection: "row",
alignItems: "center",
},
});