possible bug fix
This commit is contained in:
parent
411d44737e
commit
dbd9060591
26
main.go
26
main.go
|
@ -30,12 +30,30 @@ type StreamResponse struct {
|
||||||
const linux = "python3"
|
const linux = "python3"
|
||||||
|
|
||||||
func createStreamResponse(fromLanguage, toLanguage, message string) string {
|
func createStreamResponse(fromLanguage, toLanguage, message string) string {
|
||||||
|
var extractedMessage string
|
||||||
|
|
||||||
|
// Try to unmarshal the message to see if it's a JSON object
|
||||||
|
var temp map[string]interface{}
|
||||||
|
if err := json.Unmarshal([]byte(message), &temp); err == nil {
|
||||||
|
// Check if the response field exists in the JSON object
|
||||||
|
if response, exists := temp["response"]; exists {
|
||||||
|
extractedMessage = fmt.Sprintf("%v", response)
|
||||||
|
} else {
|
||||||
|
// If no response field, use the entire message as a fallback
|
||||||
|
extractedMessage = message
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// If unmarshalling fails, use the message as it is
|
||||||
|
extractedMessage = message
|
||||||
|
}
|
||||||
|
|
||||||
response := StreamResponse{
|
response := StreamResponse{
|
||||||
From: fromLanguage,
|
From: fromLanguage,
|
||||||
To: toLanguage,
|
To: toLanguage,
|
||||||
CreatedAt: time.Now().Format(time.RFC3339),
|
CreatedAt: time.Now().Format(time.RFC3339),
|
||||||
Response: message,
|
Response: extractedMessage,
|
||||||
}
|
}
|
||||||
|
|
||||||
jsonResp, err := json.Marshal(response)
|
jsonResp, err := json.Marshal(response)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return `{"response": "Error in preparing the message."}`
|
return `{"response": "Error in preparing the message."}`
|
||||||
|
@ -110,7 +128,8 @@ func executeTranslator(w http.ResponseWriter, message, fromLanguage, toLanguage
|
||||||
messages := make(chan string)
|
messages := make(chan string)
|
||||||
defer close(messages)
|
defer close(messages)
|
||||||
|
|
||||||
go streamResponse(w, fromLanguage, toLanguage, messages)
|
go streamResponse(w, messages)
|
||||||
|
|
||||||
cmd := exec.Command(linux, "translator/translate.py", message, fromLanguage, toLanguage)
|
cmd := exec.Command(linux, "translator/translate.py", message, fromLanguage, toLanguage)
|
||||||
output, err := cmd.StdoutPipe()
|
output, err := cmd.StdoutPipe()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
@ -126,7 +145,8 @@ func executeTranslator(w http.ResponseWriter, message, fromLanguage, toLanguage
|
||||||
|
|
||||||
scanner := bufio.NewScanner(output)
|
scanner := bufio.NewScanner(output)
|
||||||
for scanner.Scan() {
|
for scanner.Scan() {
|
||||||
messages <- string(scanner.Bytes())
|
// Directly send the translated text as a message
|
||||||
|
messages <- scanner.Text()
|
||||||
}
|
}
|
||||||
|
|
||||||
err = cmd.Wait()
|
err = cmd.Wait()
|
||||||
|
|
Loading…
Reference in New Issue