Skip to content

Commit 5780324

Browse files
committed
llama-tts : input from stdin
* tts.cpp : in case of missing text prompt, tts tries to detect an input redirection to the stdin and reads it. This enables piping text to llama-tts, input redirection and heredocuments. In case of empty text prompt the program exits with EINVAL.
1 parent 8b91d53 commit 5780324

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

examples/tts/tts.cpp

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,18 @@ enum outetts_version {
3131
#define SQR(X) ((X) * (X))
3232
#define UNCUBE(x) x < 48 ? 0 : x < 115 ? 1 : (x - 35) / 40
3333

34+
#ifdef _WIN32
35+
#include <io.h>
36+
static bool stdin_isatty() {
37+
return _isatty( _fileno(stdin) );
38+
}
39+
#else
40+
#include <unistd.h>
41+
static bool stdin_isatty() {
42+
return isatty( fileno(stdin) );
43+
}
44+
#endif
45+
3446
/**
3547
* Quantizes 24-bit RGB to xterm256 code range [16,256).
3648
*/
@@ -533,6 +545,35 @@ static std::string audio_data_from_speaker(json speaker, const outetts_version t
533545
return audio_data;
534546
}
535547

548+
static void read_stdin(std::string& in) {
549+
static constexpr const size_t size_buf = 8;
550+
551+
while (true) {
552+
char buffer[size_buf] = {0};
553+
const size_t bytes_read = fread(buffer, 1, size_buf, stdin);
554+
if (bytes_read==0) {
555+
break;
556+
}
557+
in.append(buffer, bytes_read);
558+
}
559+
}
560+
561+
static bool check_text(std::string& in) {
562+
if (in.empty()) {
563+
LOG_ERR("%s: Empty text prompt, nothing to do.\n", __func__);
564+
return false;
565+
}
566+
567+
if (in.size()==1) {
568+
if (! std::isalnum(in[0])) {
569+
LOG_ERR("%s: Weird text prompt, nothing to do.\n", __func__);
570+
return false;
571+
}
572+
}
573+
574+
return true;
575+
}
576+
536577
int main(int argc, char ** argv) {
537578
common_params params;
538579

@@ -550,6 +591,22 @@ int main(int argc, char ** argv) {
550591
return 1;
551592
}
552593

594+
if (params.prompt.empty()) {
595+
// no '-p', no '-f'.
596+
if (stdin_isatty()) {
597+
// terminal interactive mode not supported, IO would block
598+
LOG_ERR("%s: Missing text prompt, nothing to do.\n", __func__);
599+
return EINVAL;
600+
}
601+
602+
// can be a redirected input
603+
read_stdin(params.prompt);
604+
}
605+
606+
if (! check_text(params.prompt)) {
607+
return EINVAL;
608+
}
609+
553610
const int n_parallel = params.n_parallel;
554611
const int n_predict = params.n_predict;
555612

0 commit comments

Comments
 (0)