人工智能初体验(二):开发简单的图灵智能聊天工具

简介:

一 API Key申请

申请地址:http://www.tuling123.com/

中间的注册登录过程不说,最后把API Key值记录下来

wKioL1Z6wKnBTZM-AACsrY_4uSo226.png

二 核心功能开发

这个小项目的目录结构:

wKiom1Z6wLqQcmKIAAAUJMMUXq4852.png

核心功能文件TuringRobot.java,代码很简单,一看就明白,代码如下:

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
package  action;
 
import  java.io.BufferedReader;
import  java.io.IOException;
import  java.io.InputStream;
import  java.io.InputStreamReader;
import  java.io.UnsupportedEncodingException;
import  java.net.HttpURLConnection;
import  java.net.MalformedURLException;
import  java.net.URL;
import  java.net.URLEncoder;
import  java.util.regex.Matcher;
import  java.util.regex.Pattern;
 
public  class  TuringRobot {
     /**
      * 使用图灵机器人接口获取回答
     
      * @param apikey API认证
      * @param info 想要请求的问题
      * @return 获取的回复
      * */
     public  static  String getResponse(String apikey,String info){
         String httpUrl;
         try  {
             httpUrl =  "http://www.tuling123.com/openapi/api?key="  + apikey +  "&info="  + URLEncoder.encode(info, "UTF-8" );
             URL url =  new  URL(httpUrl);
             HttpURLConnection connection = (HttpURLConnection) url.openConnection();
             connection.setRequestMethod( "GET" );
             connection.setReadTimeout( 5000 );
             connection.setConnectTimeout( 5000 );
             
             InputStream inputStream = connection.getInputStream();
             BufferedReader reader =  new  BufferedReader( new  InputStreamReader(inputStream, "UTF-8" ));
             String line =  "" ;
             String reg =  "\"text\":\"(.*)?\"}" ;
             Pattern pattern = Pattern.compile(reg);
             Matcher matcher;
             while ((line = reader.readLine()) !=  null ){
                 matcher = pattern.matcher(line);
                 if (matcher.find()){
                     connection.disconnect();
                     return  matcher.group( 1 );
                 }
             }
             connection.disconnect();   
         catch  (UnsupportedEncodingException e1) {
             e1.printStackTrace();
         catch  (MalformedURLException e) {
             e.printStackTrace();
         catch  (IOException e) {
             e.printStackTrace();
         }
         return  "" ;
     }
     
     /**
      * 使用百度接口获取回答
     
      * @param key 默认值:879a6cb3afb84dbf4fc84a1df2ab7319
      * @param ApiKey 在APIStore调用服务所需要的API密钥,申请地址:http://apistore.baidu.com
      * @param info 想要请求的问题
      * @param userid 用户id 默认值:eb2edb736
     
      * @return 获取的回复
      * */
     public  static  String getResponse(String key,String ApiKey,String info,String userid){
         String httpUrl =  "http://apis.baidu.com/turing/turing/turing?" ;
         try  {
             info = URLEncoder.encode(info, "UTF-8" );  
         catch  (UnsupportedEncodingException e1) {
             e1.printStackTrace();
         }
         String httpArg =  "key="  + key +  "&info="  + info +  "&userid="  + userid;
         try  {
             URL url =  new  URL(httpUrl + httpArg);
             HttpURLConnection connection = (HttpURLConnection) url.openConnection();
             connection.setRequestMethod( "GET" );
             connection.setRequestProperty( "apikey" , ApiKey);
             
             InputStream inputStream = connection.getInputStream();
             BufferedReader reader =  new  BufferedReader( new  InputStreamReader(inputStream, "UTF-8" ));
             String line =  "" ;
             String reg =  "\"text\":\"(.*)?\",\"code\"" ;
             Pattern pattern = Pattern.compile(reg);
             Matcher matcher;
             while ((line = reader.readLine()) !=  null ){
                 matcher = pattern.matcher(line);
                 if (matcher.find()){
                     connection.disconnect();
                     return  matcher.group( 1 );
                 }
             }  
             connection.disconnect();
         catch  (MalformedURLException e) {
             e.printStackTrace();
         catch  (IOException e) {
             e.printStackTrace();
         }
         return  "" ;
         
     }
 
}

三 前台界面开发

在界面开发中有几个关键点需要注意:

(1)使用了新的线程来执行数据获取过程,并且通过SwingUtilities.invokeLater()来通知EDT更新界面。具体技术可以参考我写的这篇文章:http://www.zifangsky.cn/2015/12/java中事件分发线程(edt)与swingutilities-invokelater相关总结/

(2)本来最开始是使用了JTextArea来显示聊天记录,后来发现不能对聊天双方的记录分别左对齐和右对齐,而且也不能对聊天记录中的文字颜色和字体进行个性化设置,因此后来将聊天界面的JTextArea改成了JTextPane。这是一个强大的控件,我这里仅仅只是进行了简单使用,看代码就明白了

(3)API Key保存在配置文件config/config.txt中了

wKiom1Z6wWCxse0VAACqxU87uhk974.png

界面代码如下:

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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
package  view;
 
import  java.awt.BorderLayout;
import  java.awt.Color;
import  java.awt.Dimension;
import  java.awt.FlowLayout;
import  java.awt.Font;
import  java.awt.Toolkit;
import  java.awt.event.ActionEvent;
import  java.awt.event.ActionListener;
import  java.awt.event.KeyEvent;
import  java.awt.event.KeyListener;
import  java.awt.event.WindowEvent;
import  java.awt.event.WindowListener;
import  java.io.BufferedReader;
import  java.io.File;
import  java.io.FileNotFoundException;
import  java.io.FileReader;
import  java.io.IOException;
import  java.text.Format;
import  java.text.SimpleDateFormat;
import  java.util.Date;
import  java.util.regex.Matcher;
import  java.util.regex.Pattern;
 
import  javax.swing.JButton;
import  javax.swing.JFrame;
import  javax.swing.JMenu;
import  javax.swing.JMenuBar;
import  javax.swing.JMenuItem;
import  javax.swing.JOptionPane;
import  javax.swing.JPanel;
import  javax.swing.JScrollPane;
import  javax.swing.JTextArea;
import  javax.swing.JTextPane;
import  javax.swing.SwingUtilities;
import  javax.swing.text.BadLocationException;
import  javax.swing.text.DefaultStyledDocument;
import  javax.swing.text.MutableAttributeSet;
import  javax.swing.text.SimpleAttributeSet;
import  javax.swing.text.StyleConstants;
 
import  action.TuringRobot;
 
public  class  MainView  extends  JFrame  implements  ActionListener, WindowListener, KeyListener{
     /**
      * @author zifangsky
      * @blog www.zifangsky.cn
      * @date 2015-12-21
      * @version v1.0.0
     
      * */
     private  static  final  long  serialVersionUID = 1L;
     private  JPanel mainJPanel,tipJPanel;
     private  JScrollPane message_JScrollPane,edit_JScrollPane;
     private  JTextArea edit_JTextArea;
     private  JButton close,submit;
     private  JTextPane messageJTextPane;
     private  DefaultStyledDocument doc;
     
     private  JMenuBar jMenuBar;
     private  JMenu help;
     private  JMenuItem author,contact,version,readme;
 
     private  Font contentFont =  new  Font( "宋体" , Font.LAYOUT_NO_LIMIT_CONTEXT,  16 );   //正文字体
     private  Font menuFont =  new  Font( "宋体" , Font.LAYOUT_NO_LIMIT_CONTEXT,  14 );   //菜单字体
     private  Color buttonColor =  new  Color( 85 , 76 , 177 );   //按钮背景色
     Color inputColor1 =  new  Color( 31 , 157 , 255 );   //输入相关颜色
     Color inputColor2 =  new  Color( 51 , 51 , 51 );   //输入相关颜色
     Color outputColor1 =  new  Color( 0 , 186 , 4 );   //返回相关颜色
     Color outputColor2 =  new  Color( 51 , 51 , 51 );   //返回相关颜色
     
 
     private  DataOperating dataOperating =  null ;   //数据操作线程
     private  Runnable updateInputInterface,updateResponseInterface;   //更新界面线程
     
     private  String inputString =  "" ,responseString =  ""
     private  String key =  "" ;  
     
     public  MainView(){
         super ( "图灵智能聊天" );
         Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
         screenSize = Toolkit.getDefaultToolkit().getScreenSize();   //屏幕大小
         setPreferredSize( new  Dimension( 350 600 ));
         int  frameWidth =  this .getPreferredSize().width;   //界面宽度
         int  frameHeight =  this .getPreferredSize().height;   //界面高度
         setSize(frameWidth,frameHeight);
         setLocation((screenSize.width - frameWidth) /  2 ,(screenSize.height - frameHeight) /  2 );
         //初始化
         mainJPanel =  new  JPanel();
         tipJPanel =  new  JPanel();
         message_JScrollPane =  new  JScrollPane();
         edit_JScrollPane =  new  JScrollPane();
         messageJTextPane =  new  JTextPane();
         doc =  new  DefaultStyledDocument();
         edit_JTextArea =  new  JTextArea( 5 10 );
         close =  new  JButton( "关闭" );
         submit =  new  JButton( "发送" );     
         jMenuBar =  new  JMenuBar();
         help =  new  JMenu( "帮助" );
         author =  new  JMenuItem( "作者" );
         contact =  new  JMenuItem( "联系方式" );
         version =  new  JMenuItem( "版本" );
         readme =  new  JMenuItem( "说明" );
         
         //设置字体
         messageJTextPane.setFont(contentFont);
         edit_JTextArea.setFont(contentFont);
         close.setFont(contentFont);
         submit.setFont(contentFont);
         help.setFont(menuFont);
         author.setFont(menuFont);
         contact.setFont(menuFont);
         version.setFont(menuFont);
         readme.setFont(menuFont);
         //布局
         mainJPanel.setLayout( new  BorderLayout());
         mainJPanel.add(message_JScrollPane,BorderLayout.NORTH);
         mainJPanel.add(edit_JScrollPane,BorderLayout.CENTER);
         mainJPanel.add(tipJPanel,BorderLayout.SOUTH);
         messageJTextPane.setPreferredSize( new  Dimension( 350 350 ));
         messageJTextPane.setBackground( new  Color( 204 , 232 , 207 ));
         message_JScrollPane.getViewport().add(messageJTextPane);
         edit_JScrollPane.getViewport().add(edit_JTextArea);
         edit_JTextArea.setBackground( new  Color( 204 , 232 , 207 ));
         edit_JTextArea.requestFocus();
         tipJPanel.setLayout( new  FlowLayout(FlowLayout.RIGHT,  10 10 ));
         tipJPanel.add(close);
         tipJPanel.add(submit);
         close.setBackground(buttonColor);
         close.setForeground(Color.WHITE);
         submit.setBackground(buttonColor);
         submit.setForeground(Color.WHITE);
         
         messageJTextPane.setEditable( false );
         edit_JTextArea.setLineWrap( true );
         edit_JTextArea.setWrapStyleWord( true );
         
         jMenuBar.add(help);
         help.add(author);
         help.add(contact);
         help.add(version);
         help.add(readme);
 
         add(mainJPanel);
         setJMenuBar(jMenuBar);
         setVisible( true );
         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         addWindowListener( this );
         //获取配置文件中的配置信息
         try  {
             BufferedReader reader =  new  BufferedReader( new  FileReader( new  File( "config/config.txt" )));
             String line = reader.readLine();   //第一行不要
             Pattern pattern = Pattern.compile( "key=(.*)?" );
             Matcher matcher;
             while ((line = reader.readLine()) !=  null ){
                 matcher = pattern.matcher(line);
                 if (matcher.find())
                     key = matcher.group( 1 );
                 break
             }  
             reader.close();
         catch  (FileNotFoundException e) {
             e.printStackTrace();
         catch  (IOException e) {
             e.printStackTrace();
         }
         
         //点击事件
         close.addActionListener( this );
         submit.addActionListener( this );
         author.addActionListener( this );
         contact.addActionListener( this );
         version.addActionListener( this );
         readme.addActionListener( this );
         //键盘时间
         edit_JTextArea.addKeyListener( this );
         //输入对话,提交后触发,更新界面
         updateInputInterface =  new  Runnable() {
             public  void  run() {
                 messageJTextPane.setEditable( true );
                 
                 setInputString( "我["  + getDateString() +  "]:" , inputColor1,  true , contentFont);
                 setInputString(inputString +  "\n" , inputColor2,  false , menuFont);
                 messageJTextPane.selectAll();
                 messageJTextPane.setCaretPosition(messageJTextPane.getSelectionEnd());
                 messageJTextPane.setEditable( false );
             }
         };
         //获取到回答后触发,更新界面
         updateResponseInterface =  new  Runnable() {
             public  void  run() {
                 messageJTextPane.setEditable( true );
 
                 setResponseString( "智子["  + getDateString() +  "]:" , outputColor1,  true , contentFont);
                 setResponseString(responseString +  "\n" , outputColor2,  false , menuFont);
                 messageJTextPane.selectAll();
                 messageJTextPane.setCaretPosition(messageJTextPane.getSelectionEnd());
                 messageJTextPane.setEditable( false );
                 
                 inputString =  "" ;
                 responseString =  "" ;
                 edit_JTextArea.setText( "" );
                 edit_JTextArea.requestFocus();
                 dataOperating =  null ;
             }
         };
     }
     
     
     public  static  void  main(String[] args) {
         SwingUtilities.invokeLater( new  Runnable() {
             public  void  run() {
                 new  MainView();
             }
         });
     }
 
     /**
      * 输入的信息在界面显示出来
      * */
     private  void  setInputString(String str,Color color, boolean  bold,Font font){
         MutableAttributeSet attributeSet =  new  SimpleAttributeSet();
         StyleConstants.setForeground(attributeSet, color);   //设置文字颜色
         if (bold)
             StyleConstants.setBold(attributeSet,  true );   //设置加粗
         StyleConstants.setFontFamily(attributeSet,  "Consolas" );   //设置字体
         StyleConstants.setFontSize(attributeSet, font.getSize());   //设置字体大小
         StyleConstants.setAlignment(attributeSet, StyleConstants.ALIGN_RIGHT);   //左对齐
         insertText(str,attributeSet);
     }
     /**
      * 返回的信息在界面显示出来
      * */
     private  void  setResponseString(String str,Color color, boolean  bold,Font font){
         MutableAttributeSet attributeSet =  new  SimpleAttributeSet();
         StyleConstants.setForeground(attributeSet, color);
         if (bold)
             StyleConstants.setBold(attributeSet,  true );
         StyleConstants.setFontFamily(attributeSet,  "Consolas" );
         StyleConstants.setFontSize(attributeSet, font.getSize());
         StyleConstants.setAlignment(attributeSet, StyleConstants.ALIGN_LEFT);
         insertText(str,attributeSet);
     }
 
     /**
      * 在JTextPane中插入文字
      * */
     private  void  insertText(String str, MutableAttributeSet attributeSet) {
         messageJTextPane.setStyledDocument(doc);
         str +=  "\n" ;
         doc.setParagraphAttributes(doc.getLength(), str.length(), attributeSet,  false );
         try  {
             doc.insertString(doc.getLength(), str, attributeSet);
         catch  (BadLocationException e) {
             e.printStackTrace();
         }
     }
 
     /**
      * 点击事件
      * */
     public  void  actionPerformed(ActionEvent e) {
         if (e.getSource() == close){
             System.exit( 0 );
         }
         else  if (e.getSource() == submit){
             if (dataOperating ==  null ){
                 dataOperating =  new  DataOperating();
                 new  Thread(dataOperating).start();
             }
         }
         else  if (e.getSource() == author){
             JOptionPane.showMessageDialog( this "zifangsky" , "作者:" ,JOptionPane.INFORMATION_MESSAGE);
         }
         else  if (e.getSource() == contact){
             JOptionPane.showMessageDialog( this "邮箱:admin@zifangsky.cn\n"  +
                     "博客:www.zifangsky.cn" , "联系方式:" ,JOptionPane.INFORMATION_MESSAGE);
         }
         else  if (e.getSource() == version){
             JOptionPane.showMessageDialog( this "v1.0.0" , "版本号:" ,JOptionPane.INFORMATION_MESSAGE);
         }
         else  if (e.getSource() == readme){
             JOptionPane.showMessageDialog( this "本程序只是简单的智能聊天,没有多余的功能。源码已经在我博客进行开源,\n"  +
                     "有需求的可以在此基础上进行APP开发,移植到Android平台上去。" , "说明:" ,JOptionPane.INFORMATION_MESSAGE);
         }
         
     }
     
     /**
      * 具体的数据处理内部类
      * */
     private  class  DataOperating  implements  Runnable{
         public  void  run() {
             //获取输入
             inputString = edit_JTextArea.getText().trim();
             if (inputString ==  null  ||  "" .equals(inputString))
                 return ;
             SwingUtilities.invokeLater(updateInputInterface);
             //获取回复
             responseString = TuringRobot.getResponse(key, inputString);
             SwingUtilities.invokeLater(updateResponseInterface);
         }
         
     }
     
     /**
      * 获取当前时间的字符串
      * @return 当前时间的字符串
      * */
     private  String getDateString(){
         Date date =  new  Date();
         Format format =  new  SimpleDateFormat( "HH:mm:ss" );
         return  format.format(date);               
     }
 
     public  void  windowOpened(WindowEvent e) {
         
     }
 
     public  void  windowClosing(WindowEvent e) {
         System.exit( 0 );
     }
 
     public  void  windowClosed(WindowEvent e) {
 
     }
 
     public  void  windowIconified(WindowEvent e) {
 
     }
 
     public  void  windowDeiconified(WindowEvent e) {
 
     }
 
     public  void  windowActivated(WindowEvent e) {
         
     }
 
     public  void  windowDeactivated(WindowEvent e) {
         
     }
 
     public  void  keyTyped(KeyEvent e) {
         
     }
     /**
      * 键盘事件,键盘按下ENTER键触发
      * */
     public  void  keyPressed(KeyEvent e) {
         if (e.getKeyCode() == KeyEvent.VK_ENTER){
             if (dataOperating ==  null ){
                 dataOperating =  new  DataOperating();
                 new  Thread(dataOperating).start();
             }
         }
         
     }
 
     public  void  keyReleased(KeyEvent e) {
         
     }
 
}

四 运行效果

wKioL1Z6wbyiZlN2AACOPuFzQss301.png

wKioL1Z6wcGA_YvgAACSu28BBqg995.png



本文转自 pangfc 51CTO博客,原文链接:http://blog.51cto.com/983836259/1727742,如需转载请自行联系原作者

相关文章
|
2月前
|
机器学习/深度学习 人工智能 自然语言处理
人工智能与机器学习:开启智能新时代的密钥
人工智能与机器学习:开启智能新时代的密钥
30 0
|
3月前
|
机器学习/深度学习 人工智能 自然语言处理
springboot基于人工智能和自然语言理解技术的医院智能导医系统源码
智能导诊系统可为患者提供线上挂号智能辅助服务,患者根据提示手动输入自己的基本症状,通过智能对话方式,该系统会依据大数据一步步帮助患者“诊断”,并最终推荐就医的科室和相关专家。患者可自主选择,实现“一键挂号”。这一模式将精确的导诊服务前置,从源头上让医疗服务更高效。
373 2
|
3月前
|
Web App开发 人工智能 自然语言处理
【人工智能时代】AI赋能编程 | 自动化工具助力高效办公
【人工智能时代】AI赋能编程 | 自动化工具助力高效办公
【人工智能时代】AI赋能编程 | 自动化工具助力高效办公
|
2月前
|
人工智能 自然语言处理 人机交互
吴泳铭:拥抱人工智能驱动的产业智能革命
吴泳铭:拥抱人工智能驱动的产业智能革命
108841 485
|
2月前
|
机器学习/深度学习 人工智能 搜索推荐
未来人工智能在后端开发中的应用前景
随着人工智能技术的不断发展,后端开发领域也迎来了新的机遇与挑战。本文探讨了人工智能在后端开发中的应用前景,分析了其对传统开发模式的影响和未来发展趋势。
|
2月前
|
机器学习/深度学习 人工智能 自然语言处理
未来智能时代:人工智能技术的新趋势与挑战
在当今数字化快速发展的时代,人工智能技术正逐渐渗透到我们生活的方方面面。本文将探讨人工智能技术的新趋势和挑战,分析其对未来社会和产业的影响。
25 0
|
2月前
|
机器学习/深度学习 人工智能 自然语言处理
人工智能大模型引领智能时代的革命
随着AI技术的飞速发展,人工智能大模型正成为推动社会进步和经济发展的重要力量,比如GPT-3、BERT和其他深度学习架构,正在开启一个全新的智能时代。在人机交互、计算范式和认知协作三个领域,大模型带来了深刻的变革。那么本文就来分享一下关于大模型如何提升人机交互的自然性和智能化程度,以及它们如何影响现有的计算模式并推动新一代计算技术的演进,并探讨这些变革对未来的意义。
44 1
人工智能大模型引领智能时代的革命
|
2月前
|
人工智能 运维 数据库
未来的后端开发:人工智能与云计算的融合
【2月更文挑战第10天】 传统的后端开发一直依赖于对数据库、服务器和网络等底层技术的熟练运用,然而随着人工智能和云计算技术的飞速发展,未来的后端开发方向也将发生深刻的变革。本文将探讨人工智能与云计算在后端开发中的应用前景,以及它们将如何重塑后端开发的方式和手段。
|
3月前
|
机器学习/深度学习 人工智能 物联网
《未来智能时代下的人工智能发展趋势与挑战》
【2月更文挑战第5天】随着人工智能技术的不断发展,我们迎来了智能时代的到来。本文将探讨人工智能在未来的发展趋势和面临的挑战,分析其在各个领域的应用前景和影响。
271 1
|
1天前
|
传感器 人工智能 自动驾驶
【AI 场景】如何开发用于自动驾驶的人工智能系统?
【5月更文挑战第3天】【AI 场景】如何开发用于自动驾驶的人工智能系统?