Removed "koc" from package names

Former-commit-id: 93e426a87e8a82a83783d68cf7a814c88df375aa
This commit is contained in:
Ziver Koc 2016-01-11 17:48:02 +01:00
parent 1ab72ffbc3
commit 5b2dffeb43
56 changed files with 2289 additions and 2313 deletions

View file

@ -0,0 +1,49 @@
package se.hal.plugin.tellstick;
import se.hal.plugin.tellstick.protocols.NexaSelfLearning;
/**
* Created by Ziver on 2015-11-19.
*/
public class TelstickSerialCommNexaOnOffTest {
public static void main(String[] args) {
try {
System.out.println("Connecting to db...");
TellstickSerialComm comm = new TellstickSerialComm();
// http://developer.telldus.com/doxygen/TellStick.html
comm.connect("COM5");
//comm.connect("/dev/ttyUSB1");
Thread.sleep(1000);
NexaSelfLearning nexa = new NexaSelfLearning();
//nexa.setHouse(11772006);
nexa.setHouse(15087918);
nexa.setGroup(0);
nexa.setUnit(0);
System.out.println("Up and Running");
while(true) {
Thread.sleep(2000);
nexa.turnOn();
nexa.setUnit(0);
comm.write(nexa);
Thread.sleep(2000);
nexa.setUnit(1);
comm.write(nexa);
Thread.sleep(2000);
nexa.turnOff();
nexa.setUnit(0);
comm.write(nexa);
Thread.sleep(2000);
nexa.setUnit(1);
comm.write(nexa);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

View file

@ -0,0 +1,59 @@
package se.hal.plugin.tellstick;
import se.hal.HalContext;
import se.hal.intf.HalSensor;
import se.hal.intf.HalSensorReportListener;
import se.hal.plugin.tellstick.protocols.Oregon0x1A2D;
import zutil.db.DBConnection;
import zutil.log.CompactLogFormatter;
import zutil.log.LogUtil;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Created by Ziver on 2015-11-19.
*/
public class TelstickSerialCommTest {
private static final Logger logger = LogUtil.getLogger();
public static void main(String[] args) {
try {
LogUtil.setGlobalFormatter(new CompactLogFormatter());
LogUtil.setGlobalLevel(Level.FINEST);
logger.info("Initializing HalContext...");
HalContext.initialize();
final DBConnection db = HalContext.getDB();
logger.info("Setting up Tellstick listeners...");
TellstickSerialComm comm = new TellstickSerialComm();
comm.setListener(new HalSensorReportListener() {
@Override
public void reportReceived(HalSensor s) {
if(s instanceof Oregon0x1A2D){
logger.info("Power used: "+ ((Oregon0x1A2D)s).getTemperature() +" pulses");
try {
PreparedStatement stmt =
db.getPreparedStatement("INSERT INTO sensor_data_raw (timestamp, event_id, data) VALUES(?, ?, ?)");
stmt.setLong(1, s.getTimestamp());
stmt.setLong(2, 1);
stmt.setDouble(3, ((Oregon0x1A2D)s).getTemperature());
db.exec(stmt);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
});
comm.connect("COM5");
//comm.connect("/dev/ttyUSB1");
logger.info("Up and Running");
} catch (Exception e) {
e.printStackTrace();
}
}
}

View file

@ -0,0 +1,67 @@
/*
* Copyright (c) 2015 Ziver
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package se.hal.plugin.tellstick.protocols;
import zutil.converters.Converter;
import static org.junit.Assert.*;
public class NexaSelfLearningTest {
@org.junit.Test
public void testEncode() throws Exception {
NexaSelfLearning nexa = new NexaSelfLearning();
nexa.setHouse(11772006);
nexa.setUnit(3);
nexa.turnOn();
assertArrayEquals(
new char[]{
84, 127, 255, 24, 1, 132, 154, 138, 136, 170,
136, 168, 170, 138, 136, 168, 168, 170, 136, 170,
138, 138, 138, 138, 138, 136, 168, 170, 138, 136,
168, 170, 138, 136, 170, 138, 136, 168, 170, 43},
nexa.encode().toCharArray()
);
}
@org.junit.Test
public void decode_ON() throws Exception {
NexaSelfLearning nexa = new NexaSelfLearning();
nexa.decode(Converter.hexToByte("0x2CE81990"));
assertEquals("House Code", 11772006, nexa.getHouse());
assertEquals("Unit Code", 1, nexa.getUnit());
assertTrue("Enabled", nexa.isOn());
}
@org.junit.Test
public void decode_OFF() throws Exception {
NexaSelfLearning nexa = new NexaSelfLearning();
nexa.decode(Converter.hexToByte("0x2CE81980"));
assertEquals("House Code", 11772006, nexa.getHouse());
assertEquals("Unit Code", 1, nexa.getUnit());
assertFalse("Enabled", nexa.isOn());
}
}

View file

@ -0,0 +1,83 @@
/*
* Copyright (c) 2015 Ziver
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package se.hal.test;
import zutil.io.DynamicByteArrayStream;
import javax.sound.sampled.*;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
/**
* Created with IntelliJ IDEA.
* User: ezivkoc
* Date: 2013-12-17
* Time: 11:24
*/
public class GoogleTTSTest {
public static void main(String[] args){
try {
/* URL url = new URL("http://translate.google.com/translate_tts?q=I+love+techcrunch");
InputStream in = url.openStream();
byte[] data = getContent(in);
in.close();
*/
Clip push = AudioSystem.getClip();
URL url = new URL("http://translate.google.com/translate_tts?ie=UTF-8&q=Hello%20World&tl=en-us");
URLConnection con = url.openConnection();
con.setRequestProperty("Cookie", "JSESSIONID=UX61oaN8vRhLE5pYXAjTWg; _ga=GA1.3.53937642.1385651778; HSID=AINSMauAFJWBs84WQ; APISID=RgytV3HJnm0dWjVr/AtidsIB_LJQzDmBMc; NID=67=R0kMLqIXXiOkrU8jlk4vgqLUiWUYUZRvxjf1Un0DQbQxGKt9pXXzDv-v0zSCSqLi_YNzcZujTDDr9r_KGsiPhEMfk-oKQSKvHe-DVVuwHZb2UZraJKCBAb6mPJO6AxBExoXHzU2pHd-DI1yIMxuLyVJA9RxhM_2kB4h7U0w9WiWqRNN7sU5DPVeLpF_ScW1VH9_igIR2ACK0WHvmoZXBjXDDrnUiVJt9DjkbMpHxU1o_1PnuUXi5FmfJLjrQspI; SID=DQAAANgAAADcaXZk9dA01UfdydUwIH32OGbA0k6mhbV2GSsiqcGYTUhNqLn_Z9TAlUsizBVoG-3g-ghXzpev46P--fqcR4UACZ2iVawFbfUB44B2hBmQQsFbyjGop1smPLu3cJORBLUKQ4PiZQb23GtXYg28prWlK3IFj8Wc3AHY5yoIpnssRY24k9DybwSSVt2Ww7c4ySzfw4uXxwtbSDTy0q8lmdAorjT4R6DCJwhaCGV4ysexY-vJaQE2kiRe3fPY2z9jQ6Mi9z_XjGRamLTI_AvJj-_XdQIfv0ZSo7JiEEjTUMb10Q; PREF=ID=8bf4d3a7414e8137:U=4ebb392cf34740cf:LD=sv:CR=2:TM=1368543367:LM=1387278509:GM=1:SG=1:S=fpteokIgX46FW8tp");
con.connect();
AudioInputStream audioPush = AudioSystem.getAudioInputStream(con.getInputStream());
push.open(audioPush);
push.start();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
} catch (LineUnavailableException e) {
e.printStackTrace();
}
}
public static byte[] getContent(InputStream stream) throws IOException{
BufferedInputStream in = new BufferedInputStream(stream);
byte[] tmp = new byte[256];
int len;
DynamicByteArrayStream buff = new DynamicByteArrayStream();
while((len=in.read(tmp)) != -1){
buff.append(tmp, 0, len);
}
return buff.getBytes();
}
}

View file

@ -0,0 +1,198 @@
/*
* Copyright (c) 2015 Ziver
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package se.hal.test;
import com.darkprograms.speech.microphone.MicrophoneAnalyzer;
import com.darkprograms.speech.recognizer.FlacEncoder;
import com.darkprograms.speech.recognizer.GoogleResponse;
import javax.sound.sampled.AudioFileFormat;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class JarvisRecognizerTest {
public static void main(String[] args){
try {
new JarvisRecognizerTest();
} catch (Exception e) {
e.printStackTrace();
}
}
public JarvisRecognizerTest() throws Exception{
MicrophoneAnalyzer mic = new MicrophoneAnalyzer(AudioFileFormat.Type.WAVE);
File audioFile = new File("bin/tmp.wav");
boolean speaking = false;
while(!speaking){
mic.captureAudioToFile(audioFile);
final int THRESHOLD = 10;//YOUR THRESHOLD VALUE.
mic.open();
int ambientVolume = mic.getAudioVolume();//
int speakingVolume = -2;
do{
int volume = mic.getAudioVolume();
System.out.println(volume);
if(volume>ambientVolume+THRESHOLD){
speakingVolume = volume;
speaking = true;
Thread.sleep(1000);
System.out.println("SPEAKING");
}
if(speaking && volume+THRESHOLD<speakingVolume){
break;
}
}while(speaking);
mic.close();
}
Thread.sleep(100);
mic.close();
FlacEncoder flacEncoder = new FlacEncoder();
File flacFile = new File(audioFile + ".flac");
flacEncoder.convertWaveToFlac(audioFile, flacFile);
audioFile.delete();
Path path = Paths.get("bin/tmp.wav.flac");
byte[] data = Files.readAllBytes(path);
String request = "https://www.google.com/"+
"speech-api/v1/recognize?"+
"xjerr=1&client=speech2text&lang=en-US&maxresults=1";
URL url = new URL(request);
Proxy proxy =new Proxy(Proxy.Type.HTTP, new InetSocketAddress("www-proxy.ericsson.se", 8080));
HttpURLConnection connection = (HttpURLConnection) url.openConnection(proxy);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "audio/x-flac; rate=8000");
connection.setRequestProperty("User-Agent", "speech2text");
connection.setConnectTimeout(60000);
connection.setUseCaches (false);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.write(data);
wr.flush();
wr.close();
connection.disconnect();
flacFile.delete();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String decodedString = in.readLine();
GoogleResponse googleResponse = new GoogleResponse();
parseResponse(decodedString, googleResponse);
System.out.println(googleResponse);
}
private void parseResponse(String rawResponse, GoogleResponse googleResponse) {
if(rawResponse == null)
return;
if (!rawResponse.contains("utterance"))
return;
String array = substringBetween(rawResponse, "[", "]");
String[] parts = array.split("}");
boolean first = true;
for( String s : parts ) {
if( first ) {
first = false;
String utterancePart = s.split(",")[0];
String confidencePart = s.split(",")[1];
String utterance = utterancePart.split(":")[1];
String confidence = confidencePart.split(":")[1];
utterance = stripQuotes(utterance);
confidence = stripQuotes(confidence);
if( utterance.equals("null") ) {
utterance = null;
}
if( confidence.equals("null") ) {
confidence = null;
}
//googleResponse.setResponse(utterance);
//googleResponse.setConfidence(confidence);
} else {
String utterance = s.split(":")[1];
utterance = stripQuotes(utterance);
if( utterance.equals("null") ) {
utterance = null;
}
googleResponse.getOtherPossibleResponses().add(utterance);
}
}
}
private String substringBetween(String s, String part1, String part2) {
String sub = null;
int i = s.indexOf(part1);
int j = s.indexOf(part2, i + part1.length());
if (i != -1 && j != -1) {
int nStart = i + part1.length();
sub = s.substring(nStart, j);
}
return sub;
}
private String stripQuotes(String s) {
int start = 0;
if( s.startsWith("\"") ) {
start = 1;
}
int end = s.length();
if( s.endsWith("\"") ) {
end = s.length() - 1;
}
return s.substring(start, end);
}
}

View file

@ -0,0 +1,85 @@
/*
* Copyright (c) 2015 Ziver
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package se.hal.test;
import com.darkprograms.speech.synthesiser.Synthesiser;
import javafx.application.Application;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.stage.Stage;
import java.io.*;
import java.net.URL;
@SuppressWarnings("restriction")
public class JarvisSyntersizerTest extends Application {
public static void main(String[] args){
try {
Application a = new JarvisSyntersizerTest();
a.launch();
} catch (Exception e) {
e.printStackTrace();
}
}
public JarvisSyntersizerTest(){
}
/**
* Returns the URL to the given file
*
* @param path is the path to the file (no / if not absolute path)
* @return A URL object for the file
*/
public static URL findURL(String path){
return Thread.currentThread().getContextClassLoader().getResource(path);
}
@Override
public void start(Stage arg0) throws Exception {
Synthesiser synthesiser = new Synthesiser("auto");
String language = synthesiser.detectLanguage("hi what is your name?");
System.out.println(language);
InputStream is = synthesiser.getMP3Data("hi what is your name?");
BufferedInputStream buff = new BufferedInputStream(is);
DataInputStream di = new DataInputStream(buff);
File f = new File("bin\\tmp.mp3");
FileOutputStream fos = new FileOutputStream(f);
while(di.available() != 0){
fos.write(di.readByte());
}
fos.close();
URL resource = findURL("tmp.mp3");
Media hit = new Media(resource.toURI().toString());
MediaPlayer mediaPlayer = new MediaPlayer(hit);
mediaPlayer.play();
}
}

View file

@ -0,0 +1,63 @@
/*
* Copyright (c) 2015 Ziver
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package se.hal.test;
import edu.cmu.sphinx.api.Configuration;
import edu.cmu.sphinx.api.LiveSpeechRecognizer;
import edu.cmu.sphinx.api.SpeechResult;
import edu.cmu.sphinx.result.WordResult;
public class LiveSpeechRecognizerTest {
public static void main(String[] args) throws Exception {
System.out.println("Loading models...");
Configuration configuration = new Configuration();
// Set path to acoustic model.
configuration.setAcousticModelPath("resource:/edu/cmu/sphinx/models/en-us/en-us");
// Set path to dictionary.
configuration.setDictionaryPath("resource:/edu/cmu/sphinx/models/en-us/cmudict-en-us.dict");
// Set language model.
configuration.setLanguageModelPath("resource:/edu/cmu/sphinx/models/en-us/en-us.lm.dmp");
System.out.println("Listening...");
LiveSpeechRecognizer recognizer = new LiveSpeechRecognizer(configuration);
// Start recognition process pruning previously cached data.
recognizer.startRecognition(false);
SpeechResult result = recognizer.getResult();
// Pause recognition process. It can be resumed then with startRecognition(false).
recognizer.stopRecognition();
// Print utterance string without filler words.
System.out.println("Hypothesis: " + result.getHypothesis());
// Get individual words and their times.
for (WordResult r : result.getWords()) {
System.out.println("Word: "+r);
}
// Save lattice in a graphviz format.
result.getLattice().dumpDot("lattice.dot", "lattice");
}
}

50
test/se/hal/test/MaryTTS.java Executable file
View file

@ -0,0 +1,50 @@
/*
* Copyright (c) 2015 Ziver
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package se.hal.test;
import marytts.MaryInterface;
import marytts.client.RemoteMaryInterface;
import marytts.util.data.audio.AudioPlayer;
import javax.sound.sampled.AudioInputStream;
import java.util.Set;
/**
* Created with IntelliJ IDEA.
* User: ezivkoc
* Date: 2013-12-17
* Time: 12:39
*/
public class MaryTTS {
public static void main(String[] args) throws Exception {
MaryInterface marytts = new RemoteMaryInterface("127.0.0.1", 59125);
Set<String> voices = marytts.getAvailableVoices();
marytts.setVoice(voices.iterator().next());
AudioInputStream audio = marytts.generateAudio("Hello world.");
AudioPlayer player = new AudioPlayer(audio);
player.start();
player.join();
System.exit(0);
}
}

View file

@ -0,0 +1,86 @@
/*
* Copyright (c) 2015 Ziver
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package se.hal.test;
import com.darkprograms.speech.microphone.MicrophoneAnalyzer;
import edu.cmu.sphinx.api.Configuration;
import edu.cmu.sphinx.api.SpeechResult;
import edu.cmu.sphinx.api.StreamSpeechRecognizer;
import edu.cmu.sphinx.result.WordResult;
import javax.sound.sampled.AudioFileFormat;
import java.io.File;
import java.io.FileInputStream;
/**
* A simple example that shows how to transcribe a continuous audio file that
* has multiple utterances in it.
*/
public class TranscriberDemo {
public static void main(String[] args) throws Exception {
System.out.println("Loading models...");
Configuration configuration = new Configuration();
// Load model from the jar
configuration.setAcousticModelPath("resource:/edu/cmu/sphinx/models/en-us/en-us");
// You can also load model from folder
// configuration.setAcousticModelPath("file:en-us");
configuration.setDictionaryPath("resource:/edu/cmu/sphinx/models/en-us/cmudict-en-us.dict");
configuration.setLanguageModelPath("resource:/edu/cmu/sphinx/models/en-us/en-us.lm.dmp");
MicrophoneAnalyzer mic = new MicrophoneAnalyzer(AudioFileFormat.Type.WAVE);
StreamSpeechRecognizer recognizer = new StreamSpeechRecognizer(configuration);
File audioFile = File.createTempFile("input", "wav");
while(true) {
System.out.println("Listening...");
mic.captureAudioToFile(audioFile);
try {
Thread.sleep(3000);
} catch (Exception e) {}
mic.close();
System.out.println("Done");
// Simple recognition with generic model
recognizer.startRecognition(new FileInputStream(audioFile));
SpeechResult result;
while ((result = recognizer.getResult()) != null) {
System.out.format("Hypothesis: %s\n", result.getHypothesis());
System.out.println("List of recognized words and their times:");
for (WordResult r : result.getWords()) {
System.out.println(r);
}
System.out.println("Best 3 hypothesis:");
for (String s : result.getNbest(3))
System.out.println(s);
}
recognizer.stopRecognition();
}
}
}

View file

@ -0,0 +1,169 @@
package se.hal.util;
import org.junit.Before;
import org.junit.Test;
import java.util.Calendar;
import static org.junit.Assert.assertEquals;
public class TimeUtilityTest {
private long currentTime_UTC;
private Calendar referenceCalendar_LOCAL;
@Before
public void setup(){
currentTime_UTC = System.currentTimeMillis();
referenceCalendar_LOCAL = Calendar.getInstance();
referenceCalendar_LOCAL.setTimeInMillis(currentTime_UTC);
}
// Test flooring LOCAL time to the closes day
@Test
public void testDayStart_LOCAL_ForCurrentTime(){
long thisPeriodStartedAt = TimeUtility.getTimestampPeriodStart_LOCAL(TimeUtility.DAY_IN_MS, currentTime_UTC);
Calendar testCalendar = Calendar.getInstance();
testCalendar.setTimeInMillis(thisPeriodStartedAt);
assertEquals("millisecond is wrong", 0, testCalendar.get(Calendar.MILLISECOND));
assertEquals("second is wrong", 0, testCalendar.get(Calendar.SECOND));
assertEquals("minute is wrong", 0, testCalendar.get(Calendar.MINUTE));
assertEquals("hour is wrong", 0, testCalendar.get(Calendar.HOUR_OF_DAY));
assertEquals("day is wrong", referenceCalendar_LOCAL.get(Calendar.DAY_OF_YEAR), testCalendar.get(Calendar.DAY_OF_YEAR));
}
// Test flooring LOCAL time to the closes hour
@Test
public void testHourStart_LOCAL_ForCurrentTime(){
long thisPeriodStartedAt = TimeUtility.getTimestampPeriodStart_LOCAL(TimeUtility.HOUR_IN_MS, currentTime_UTC);
Calendar testCalendar = Calendar.getInstance();
testCalendar.setTimeInMillis(thisPeriodStartedAt);
assertEquals("millisecond is wrong", 0, testCalendar.get(Calendar.MILLISECOND));
assertEquals("second is wrong", 0, testCalendar.get(Calendar.SECOND));
assertEquals("minute is wrong", 0, testCalendar.get(Calendar.MINUTE));
assertEquals("hour is wrong", referenceCalendar_LOCAL.get(Calendar.HOUR_OF_DAY), testCalendar.get(Calendar.HOUR_OF_DAY));
assertEquals("day is wrong", referenceCalendar_LOCAL.get(Calendar.DAY_OF_YEAR), testCalendar.get(Calendar.DAY_OF_YEAR));
}
// Test flooring LOCAL time to the closes minute
@Test
public void testMinuteStart_LOCAL_ForCurrentTime(){
long thisPeriodStartedAt = TimeUtility.getTimestampPeriodStart_LOCAL(TimeUtility.MINUTES_IN_MS, currentTime_UTC);
Calendar testCalendar = Calendar.getInstance();
testCalendar.setTimeInMillis(thisPeriodStartedAt);
assertEquals("millisecond is wrong", 0, testCalendar.get(Calendar.MILLISECOND));
assertEquals("second is wrong", 0, testCalendar.get(Calendar.SECOND));
assertEquals("minute is wrong", referenceCalendar_LOCAL.get(Calendar.MINUTE), testCalendar.get(Calendar.MINUTE));
assertEquals("hour is wrong", referenceCalendar_LOCAL.get(Calendar.HOUR_OF_DAY), testCalendar.get(Calendar.HOUR_OF_DAY));
assertEquals("day is wrong", referenceCalendar_LOCAL.get(Calendar.DAY_OF_YEAR), testCalendar.get(Calendar.DAY_OF_YEAR));
}
// Test flooring LOCAL time to the closes second
@Test
public void testSecondStart_LOCAL_ForCurrentTime(){
long thisPeriodStartedAt = TimeUtility.getTimestampPeriodStart_LOCAL(TimeUtility.SECOND_IN_MS, currentTime_UTC);
Calendar testCalendar = Calendar.getInstance();
testCalendar.setTimeInMillis(thisPeriodStartedAt);
assertEquals("millisecond is wrong", 0, testCalendar.get(Calendar.MILLISECOND));
assertEquals("second is wrong", referenceCalendar_LOCAL.get(Calendar.SECOND), testCalendar.get(Calendar.SECOND));
assertEquals("minute is wrong", referenceCalendar_LOCAL.get(Calendar.MINUTE), testCalendar.get(Calendar.MINUTE));
assertEquals("hour is wrong", referenceCalendar_LOCAL.get(Calendar.HOUR_OF_DAY), testCalendar.get(Calendar.HOUR_OF_DAY));
assertEquals("day is wrong", referenceCalendar_LOCAL.get(Calendar.DAY_OF_YEAR), testCalendar.get(Calendar.DAY_OF_YEAR));
}
// Test flooring UTC time to the closes day
@Test
public void testDayStart_UTC_ForCurrentTime(){
long thisPeriodStartedAt = TimeUtility.getTimestampPeriodStart_UTC(TimeUtility.DAY_IN_MS, currentTime_UTC);
assertEquals("millisecond is wrong", 0, TimeUtility.getMillisecondInSecondFromTimestamp(thisPeriodStartedAt));
assertEquals("second is wrong", 0, TimeUtility.getSecondOfMinuteFromTimestamp(thisPeriodStartedAt));
assertEquals("minute is wrong", 0, TimeUtility.getMinuteOfHourFromTimestamp(thisPeriodStartedAt));
assertEquals("hour is wrong", 0, TimeUtility.getHourOfDayFromTimestamp(thisPeriodStartedAt));
assertEquals("day is wrong", TimeUtility.getDaysFromTimestamp(currentTime_UTC), TimeUtility.getDaysFromTimestamp(thisPeriodStartedAt));
}
// Test flooring UTC time to the closes hour
@Test
public void testHourStart_UTC_ForCurrentTime(){
long thisPeriodStartedAt = TimeUtility.getTimestampPeriodStart_UTC(TimeUtility.HOUR_IN_MS, currentTime_UTC);
Calendar testCalendar = Calendar.getInstance();
testCalendar.setTimeInMillis(thisPeriodStartedAt);
assertEquals("millisecond is wrong", 0, TimeUtility.getMillisecondInSecondFromTimestamp(thisPeriodStartedAt));
assertEquals("second is wrong", 0, TimeUtility.getSecondOfMinuteFromTimestamp(thisPeriodStartedAt));
assertEquals("minute is wrong", 0, TimeUtility.getMinuteOfHourFromTimestamp(thisPeriodStartedAt));
assertEquals("hour is wrong", TimeUtility.getHourOfDayFromTimestamp(currentTime_UTC), TimeUtility.getHourOfDayFromTimestamp(thisPeriodStartedAt));
assertEquals("day is wrong", TimeUtility.getDaysFromTimestamp(currentTime_UTC), TimeUtility.getDaysFromTimestamp(thisPeriodStartedAt));
}
// Test flooring UTC time to the closes minute
@Test
public void testMinuteStart_UTC_ForCurrentTime(){
long thisPeriodStartedAt = TimeUtility.getTimestampPeriodStart_UTC(TimeUtility.MINUTES_IN_MS, currentTime_UTC);
Calendar testCalendar = Calendar.getInstance();
testCalendar.setTimeInMillis(thisPeriodStartedAt);
assertEquals("millisecond is wrong", 0, TimeUtility.getMillisecondInSecondFromTimestamp(thisPeriodStartedAt));
assertEquals("second is wrong", 0, TimeUtility.getSecondOfMinuteFromTimestamp(thisPeriodStartedAt));
assertEquals("minute is wrong", TimeUtility.getMinuteOfHourFromTimestamp(currentTime_UTC), TimeUtility.getMinuteOfHourFromTimestamp(thisPeriodStartedAt));
assertEquals("hour is wrong", TimeUtility.getHourOfDayFromTimestamp(currentTime_UTC), TimeUtility.getHourOfDayFromTimestamp(thisPeriodStartedAt));
assertEquals("day is wrong", TimeUtility.getDaysFromTimestamp(currentTime_UTC), TimeUtility.getDaysFromTimestamp(thisPeriodStartedAt));
}
// Test flooring UTC time to the closes second
@Test
public void testSecondStart_UTC_ForCurrentTime(){
long thisPeriodStartedAt = TimeUtility.getTimestampPeriodStart_UTC(TimeUtility.SECOND_IN_MS, currentTime_UTC);
Calendar testCalendar = Calendar.getInstance();
testCalendar.setTimeInMillis(thisPeriodStartedAt);
assertEquals("millisecond is wrong", 0, TimeUtility.getMillisecondInSecondFromTimestamp(thisPeriodStartedAt));
assertEquals("second is wrong", TimeUtility.getSecondOfMinuteFromTimestamp(currentTime_UTC), TimeUtility.getSecondOfMinuteFromTimestamp(thisPeriodStartedAt));
assertEquals("minute is wrong", TimeUtility.getMinuteOfHourFromTimestamp(currentTime_UTC), TimeUtility.getMinuteOfHourFromTimestamp(thisPeriodStartedAt));
assertEquals("hour is wrong", TimeUtility.getHourOfDayFromTimestamp(currentTime_UTC), TimeUtility.getHourOfDayFromTimestamp(thisPeriodStartedAt));
assertEquals("day is wrong", TimeUtility.getDaysFromTimestamp(currentTime_UTC), TimeUtility.getDaysFromTimestamp(thisPeriodStartedAt));
}
// Test printing converting milliseconds to text
@Test
public void testMsToString(){
//low values
assertEquals("0days+00:00:00.000", TimeUtility.msToString(0));
assertEquals("0days+00:00:00.001", TimeUtility.msToString(1));
assertEquals("0days+00:00:01.000", TimeUtility.msToString(TimeUtility.SECOND_IN_MS));
assertEquals("0days+00:01:00.000", TimeUtility.msToString(TimeUtility.MINUTES_IN_MS));
assertEquals("0days+00:05:00.000", TimeUtility.msToString(TimeUtility.FIVE_MINUTES_IN_MS));
assertEquals("0days+01:00:00.000", TimeUtility.msToString(TimeUtility.HOUR_IN_MS));
assertEquals("1days+00:00:00.000", TimeUtility.msToString(TimeUtility.DAY_IN_MS));
assertEquals("7days+00:00:00.000", TimeUtility.msToString(TimeUtility.WEEK_IN_MS));
//high values
assertEquals("0days+00:00:00.999", TimeUtility.msToString(999));
assertEquals("0days+00:00:59.000", TimeUtility.msToString(TimeUtility.SECOND_IN_MS*59));
assertEquals("0days+00:59:00.000", TimeUtility.msToString(TimeUtility.MINUTES_IN_MS*59));
assertEquals("0days+23:00:00.000", TimeUtility.msToString(TimeUtility.HOUR_IN_MS*23));
assertEquals("369days+00:00:00.000", TimeUtility.msToString(TimeUtility.DAY_IN_MS*369));
//high overflow values
assertEquals("0days+00:00:01.999", TimeUtility.msToString(1999));
assertEquals("0days+00:02:39.000", TimeUtility.msToString(TimeUtility.SECOND_IN_MS*159));
assertEquals("0days+02:39:00.000", TimeUtility.msToString(TimeUtility.MINUTES_IN_MS*159));
assertEquals("5days+03:00:00.000", TimeUtility.msToString(TimeUtility.HOUR_IN_MS*123));
//combinations
long ms = (TimeUtility.DAY_IN_MS*999) + (TimeUtility.HOUR_IN_MS*23) + (TimeUtility.MINUTES_IN_MS*59) + (TimeUtility.SECOND_IN_MS*59) + 999;
assertEquals("999days+23:59:59.999", TimeUtility.msToString(ms));
}
// Test printing converting milliseconds to text for a negative time
@Test(expected=NumberFormatException.class)
public void testMsToStringForNegativeArgument(){
//low values
TimeUtility.msToString(-1);
}
}