Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: s2t added #156

Open
wants to merge 6 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 0 additions & 3 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,9 @@ import StarredChatsPage from "./pages/starred-chat-page";
import { AppContext } from "./utils/app-context";
import { CookiesProvider } from "react-cookie";
import { send } from "./components/websocket";

import { toast, Toaster } from "react-hot-toast";

import { socket } from "./socket";
import { map, reduce, uniq } from "lodash";

import { initialState } from "./utils/initial-states";
import { UserInput } from "./components/UserInput";
import { useDispatch, useSelector } from "react-redux";
Expand Down
141 changes: 141 additions & 0 deletions src/components/recorder/index.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
import { useState, useEffect } from "react";
import stop from "./stop2.gif";
import start from "./start2.svg";
import styles from "./styles.module.css";
import toast from "react-hot-toast";
import axios from "axios";
import {
logToAndroid,
triggerEventInAndroid,
} from "../../utils/android-events";
import FullScreenLoader from "../FullScreenLoader";

const RenderVoiceRecorder = ({ setInputMsg }) => {
const [mediaRecorder, setMediaRecorder] = useState(null);
const [apiCallStatus, setApiCallStatus] = useState("idle");
const startRecording = async () => {
try {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
const recorder = new MediaRecorder(stream);

recorder.ondataavailable = (event) => {
if (event.data.size > 0) {
makeComputeAPICall(event.data);
}
};

recorder.start();
setMediaRecorder(recorder);
} catch (error) {
console.error(error);
setApiCallStatus("error");
toast.error(`Something went wrong in recording audio`);
}
};

const stopRecording = () => {
if (mediaRecorder && mediaRecorder.state === "recording") {
mediaRecorder.stop();
}
};

useEffect(() => {
return () => {
if (mediaRecorder) {
mediaRecorder.stop();
}
};
}, [mediaRecorder]);


const makeComputeAPICall = async (blob) => {
setApiCallStatus('processing');
toast.success(`प्रतीक्षा करें ...`);
let data = new FormData();
data.append("file", blob, "audio.wav");
data.append("disablePostProcessor", "true");

const apiEndpoint = localStorage.getItem('promptUrl') || process.env.REACT_APP_BASE_URL;
const authToken = localStorage.getItem('promptToken');
let config = {
method: "post",
maxBodyLength: Infinity,
url: `${apiEndpoint}/aitools/asr?language=hi`,
headers: {
'Authorization': `Bearer ${authToken}`,
},
data: data,
};

function replaceDandaCharacter(inputString) {
const regex = /।/g;
const replacedString = inputString.replace(regex, "");
return replacedString;
}

axios
.request(config)
.then((response) => {
setInputMsg(replaceDandaCharacter(response.data.text));
setApiCallStatus("idle");
})
.catch((error) => {
console.log(error);
setApiCallStatus("error");
toast.error(`Something went wrong :${error.message}`);
});
};


return (
<div>
{apiCallStatus === "processing" && <FullScreenLoader loading />}
<div>
{mediaRecorder && mediaRecorder.state === "recording" ? (
<div className={styles.center}>
<img
src={stop}
alt="stopIcon"
width="30px"
onClick={() => {
stopRecording();
}}
style={{ cursor: "pointer" }}
/>
</div>
) : (
<div className={styles.center}>
<img
src={start}
alt="startIcon"
onClick={async(ev) => {
ev.preventDefault();
logToAndroid(`debug isPermissionGranted`);
startRecording()
try {
const isAvailable = await window?.androidInteract?.isPermissionGranted();
logToAndroid(`debug isPermissionGranted return value:${isAvailable}`);
if(isAvailable){
logToAndroid(`debug isPermissionGranted available`);
startRecording()
}
else
{
logToAndroid(`debug isPermissionGranted false`);
triggerEventInAndroid("onMicClick");}
} catch (err) {
logToAndroid(
`debug error in getting mic permission:${JSON.stringify(err)}`
);
}
}}
style={{ cursor: "pointer" }}
/>
</div>
)}
</div>
</div>
);
};

export default RenderVoiceRecorder;
12 changes: 12 additions & 0 deletions src/components/recorder/start2.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added src/components/recorder/stop2.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
12 changes: 12 additions & 0 deletions src/components/recorder/styles.module.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
.center {
display: block;
height: 100%;
width: 100%;
-webkit-tap-highlight-color: transparent;
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
14 changes: 3 additions & 11 deletions src/components/search/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { useEffect, useRef, useState } from "react";
import styles from "./index.module.css";
import { FaSearch, FaTimes } from "react-icons/fa";
import { FaSearch } from "react-icons/fa";
import RenderVoiceRecorder from "../recorder";
import { Box } from "@chakra-ui/react";


Expand Down Expand Up @@ -61,16 +62,7 @@ function SearchBar({ onChange }) {

{showSearchInput ? (
<div className={styles.voiceIcon} style={{ padding: "5px" }}>
<FaTimes
style={{ top: "14px", right: "12px", fontSize: "20px" ,color:'#2E3192'}}
onClick={() => {
setIsFocused(false);
setIsHovered(false);
setValue("");
setShowSearchInput(false);
}}
/>

<RenderVoiceRecorder setInputMsg={setValue}/>
</div>
) : (
<FaSearch
Expand Down
2 changes: 1 addition & 1 deletion src/components/websocket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export const send = (
socketOld: any,
media: any
): void => {
console.log({session,toUser})

if (toUser?.number === null || toUser?.number === 'null') {
socket?.emit('botRequest', {
content: {
Expand Down
1 change: 0 additions & 1 deletion src/store/actions/fetchHistory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ export const fetchHistory = createAsyncThunk<User, any>(
async (data, thunk) => {
try {
const url = getConvHistoryUrl(data);
console.log({url})
const response = await axios.get(url);
return response?.data?.result?.records;
} catch (err) {
Expand Down
2 changes: 1 addition & 1 deletion src/utils/android-events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import moment from "moment";

export const logToAndroid = (text: string) => {
window && window?.androidInteract?.log(text);
// console.log(text);

};

export const sendEventToAndroid = (key: string, value: any) => {
Expand Down
4 changes: 2 additions & 2 deletions src/utils/normalize-chats.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import moment from 'moment';
export const normalizedChat = (chats: any): any => {
const sortedChats = sortBy(
filter(
chats?.map((chat: any) => {console.log(chat); return {
chats?.map((chat: any) => ( {
...chat,
disabled: true,
text: chat?.payload?.text === 'This conversation has expired now. Please contact your state admin to seek help with this.' ? "यह फॉर्म समाप्त हो गया है !": chat?.payload?.text,
Expand All @@ -19,7 +19,7 @@ export const normalizedChat = (chats: any): any => {
toUpper(JSON.parse(localStorage.getItem('currentUser'))?.startingMessage),
// toUpper(currentUser?.startingMessage),
time: moment(chat.sentTimestamp || chat.repliedTimestamp).valueOf()
}}),
})),
{ isIgnore: false }
),
['time', 'messageState']
Expand Down