TTSProcessor.java :  » XML » alttext » nl » dedicon » converter » dtbook » processors » Java Open Source

Java Open Source » XML » alttext 
alttext » nl » dedicon » converter » dtbook » processors » TTSProcessor.java
/*
 * Copyright (C) 2010 Dedicon <http://dedicon.nl>

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

Linking altText statically or dynamically with other modules 
is making a combined work based on altText. Thus, the terms and 
conditions of the GNU General Public License cover
the whole combination.  In addition, as a special exception, 
the copyright holders of altText give you permission to
combine altText program with free software programs or libraries 
that are released under the GNU LGPL or the Common Public License version 1.0. 
You may copy and distribute such a system following the terms 
of the GNU GPL for altText and the licenses of the other code
concerned, provided that you include the source code of that other 
code when and as the GNU GPL requires distribution of source code.

Note that people who make modified versions of altText are not obligated to 
grant this special exception for their modified versions; it is their 
choice whether to do so. The GNU General Public License gives permission 
to release a modified version without this exception; this exception 
also makes it possible to release a modified version which carries
forward this exception.

You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

Author : Javier Asensio Cubero capitan{.}cambio{@}gmail{.}com
 */
package nl.dedicon.converter.dtbook.processors;

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.EventObject;
import java.util.LinkedList;
import java.util.logging.Logger;

import javax.xml.stream.Location;

import nl.dedicon.converter.core.ConverterUnrecoverableException;
import nl.dedicon.converter.core.Processor;
import nl.dedicon.converter.core.io.Package;
import nl.dedicon.converter.core.util.Notifier;
import nl.dedicon.converter.dtbook.io.DaisyXmlToOdtPackage;

import nl.dedicon.converter.dtbook.processors.util.OutputBaseDirConfigurable;
import nl.dedicon.converter.dtbook.processors.util.OutputBaseDirConfigurator;

import org.apache.commons.logging.impl.Log4JLogger;
import org.apache.log4j.BasicConfigurator;
import org.daisy.pipeline.core.InputListener;
import org.daisy.pipeline.core.PipelineCore;
import org.daisy.pipeline.core.event.BusListener;
import org.daisy.pipeline.core.event.CoreMessageEvent;
import org.daisy.pipeline.core.event.EventBus;
import org.daisy.pipeline.core.event.JobStateChangeEvent;
import org.daisy.pipeline.core.event.MessageEvent;
import org.daisy.pipeline.core.event.RequestEvent;
import org.daisy.pipeline.core.event.StateChangeEvent;
import org.daisy.pipeline.core.event.TaskMessageEvent;
import org.daisy.pipeline.core.event.TaskStateChangeEvent;
import org.daisy.pipeline.core.event.UserReplyEvent;
import org.daisy.pipeline.core.script.Job;
import org.daisy.pipeline.core.script.Script;
import org.daisy.pipeline.core.script.Task;
import org.daisy.util.xml.stax.ExtendedLocationImpl;
 
// TODO: Auto-generated Javadoc
/**
 * The Class TTSProcessor transforms the dtbook in to an mp3 using the TSS system.
 */
public class TTSProcessor extends Processor implements OutputBaseDirConfigurable{

  /** The m base path. */
  private String mBasePath;
  
  /** The Constant SCRIPT_PATH. */
  private static final String SCRIPT_PATH  = System.getProperty("user.dir")+"\\lib\\pipeline\\scripts\\create_distribute\\dtb\\DutchearNarrator.taskScript";
  
  /** The logger. */
  private Logger logger = Logger
      .getLogger("nl.dedicon.converter.ooobased.processors");
  
  /**
   * Instantiates a new tTS processor.
   */
  public TTSProcessor() {
    new OutputBaseDirConfigurator().configure((OutputBaseDirConfigurable)this);
  }
  
  /* (non-Javadoc)
   * @see nl.dedicon.converter.core.Processor#doPerform(nl.dedicon.converter.core.io.Package)
   */
  @Override
  protected void doPerform(Package pack) {
    DaisyXmlToOdtPackage dPack=(DaisyXmlToOdtPackage)pack;
    logger.info("Performing " + this.getClass().getName());

    Notifier.getInstance().notify("CONVERTING TO MP3 (this may take a while)");
    try{
      //dPack.getDtbook().save(new File(dPack.getOriginalFile().getPath()));
      String inputFile = dPack.getOriginalFile().getPath();
      String outputDir = dPack.getOriginalFile().getOutputDir(mBasePath);
      
      EventBus.getInstance().subscribe(new DaisyLogger(), MessageEvent.class);
            EventBus.getInstance().subscribe(new DaisyLogger(), StateChangeEvent.class);
            logger.info("Launching the pipeline job");
      BasicConfigurator.configure();  
      PipelineCore core = new PipelineCore(null,new File("lib\\pipeline"));
      Script script = core.newScript(new File(this.SCRIPT_PATH).toURI().toURL());
      Job job = new Job(script);
      //job paramters
      job.setParameterValue("input", inputFile);
      job.setParameterValue("outputPath", outputDir);
      job.setParameterValue("multiLang", "true");      
      core.execute(job);
      //inside pipeline's process some files are not closed, so we force the objects to finalize
      
      core=null;
      job=null;
      script=null;
      System.gc();

      //merge the generated mp3 files
      logger.info("merging the generated files");
      String fileName = dPack.getOriginalFile().getPath();
      fileName = fileName.substring(fileName.lastIndexOf(File.separator),
          fileName.length());
      fileName = fileName.substring(0, fileName.lastIndexOf(".dtbook"));
      String output = System.getProperty("user.dir")+File.separator+dPack.getOriginalFile().getOutputDir(mBasePath)+
              "tts";
      
      File outputTTSDir= new File(output);
      File smilDir = new File(dPack.getOriginalFile().getOutputDir(mBasePath)+File.separator+"z3986");
      //delete previous files
      try{
        for(File f : outputTTSDir.listFiles()){
          f.delete();
        }
      }catch (NullPointerException e) {}
      outputTTSDir.delete();
      deleteTmpFolders(dPack);
    /*  boolean res= smilDir.renameTo(outputTTSDir);
      if(!res){
        logger.warning("I coudnt move the smil dir!!");
      }*/
      
      logger.info("TTS conversion done");
      dPack.setResultPath(outputTTSDir.getAbsolutePath());
    }catch (ConverterUnrecoverableException cue) {
      throw cue;
    }catch (Exception e) {
      String msg = "Error calling TTS :"+e.getMessage();
      this.logger.severe(msg);
      throw new ConverterUnrecoverableException(msg,e);
    }
  }

  
  private void deleteTmpFolders(DaisyXmlToOdtPackage dPack) {
    File daisyTemp = new File(dPack.getOriginalFile().getOutputDir(mBasePath)+File.separator+"pipeline__temp");
    File daisyTemp1 = new File(daisyTemp, "tmp1");
    File speechGen = new File(daisyTemp, "speechgen");
    for(File f: daisyTemp1.listFiles()){
      
      logger.info(f.getAbsolutePath()+" "+f.canWrite()+" "+f.delete());
    }
    for(File f: speechGen.listFiles()){
//      f.delete();
      logger.info(f.getAbsolutePath()+" "+f.canWrite()+" "+f.delete());

    }
    daisyTemp1.delete();
    speechGen.delete();
    daisyTemp.delete();
    //File z3986 = new File(dPack.getOriginalFile().getOutputDir(mBasePath)+File.separator+"z3986");
    //for(File f: z3986.listFiles()){
    //  f.delete();
    //}
    
  
    //z3986.delete();
  }

  /* (non-Javadoc)
   * @see nl.dedicon.converter.dtbook.processors.util.OutputBaseDirConfigurable#setOutputBaseDir(java.lang.String)
   */
  @Override
  public void setOutputBaseDir(String baseDir) {
    this.mBasePath = baseDir;
  }
}
/** Process the daisy events to log them */
class DaisyLogger implements InputListener, BusListener{
  private Logger logger = Logger
  .getLogger("nl.dedicon.converter.ooobased.processors");
  @Override
  public UserReplyEvent getUserReply(RequestEvent arg0) {

    return null;
  }

  @Override
  public void received(EventObject event) {
      // we are subscribing to MessageEvent and StateChangeEvent

        try {
            if (event instanceof MessageEvent) {
                MessageEvent sme = (MessageEvent) event;
                StringBuilder message = new StringBuilder();

                String type = null;
                switch (sme.getType()) {
                case INFO:
                    type = "INFO";
                    break;
                case INFO_FINER:
                    type = "INFO_FINER";
                    break;    
                case WARNING:
                    type = "WARNING";
                    break;
                case ERROR:
                    type = "ERROR";
                    break;
                case DEBUG:
                    type = "DEBUG";
                    break;
                }

                String who = null;
                if (sme instanceof CoreMessageEvent) {
                    who = "Pipeline Core";
                } else if (sme instanceof TaskMessageEvent) {
                    Task task = (Task) sme.getSource();
                    if (task.getTransformerInfo() != null) {
                        who = task.getTransformerInfo().getNiceName();
                    } else {
                        who = task.getName();
                    }
                } else {
                    who = "???";
                }

                StringBuilder location = new StringBuilder();
                if (sme.getLocation() != null) {
                    Location loc = sme.getLocation();
                    String sysId = loc.getSystemId();
                    if (sysId != null && sysId.length() > 0) {
                        File file = new File(sysId);
                        location.append(" Location: ");
                        location.append(file.getPath());
                        if (loc.getLineNumber() > -1) {
                            location.append(' ');
                            location.append(loc.getLineNumber());
                            if (loc.getColumnNumber() > -1) {
                                location.append(':');
                                location.append(loc.getColumnNumber());
                            }
                        }
                    }
                                   
                    //mg20070904: printing extended location info
                    if(loc instanceof ExtendedLocationImpl) {                                                
                      ExtendedLocationImpl eLoc = (ExtendedLocationImpl)loc;                      
                      ExtendedLocationImpl.InformationType[] types = ExtendedLocationImpl.InformationType.values();                                            
                      for (int i = 0; i < types.length; i++) {                        
                        location.append("\n\t");
                        location.append(types[i].toString()).append(':').append(' ');
                        String value = eLoc.getExtendedLocationInfo(types[i]);
                        location.append(value==null?"N/A":value);                                
            }                      
                    }
                    
                }//if (sme.getLocation() != null)

                message.append('[');
                message.append(type);
                message.append(',').append(' ');
                message.append(who);
                message.append(']').append(' ');
                message.append(sme.getMessage());
                message.append(location.toString());

                logger.info(message.toString());

            } else if (event instanceof StateChangeEvent) {
                StateChangeEvent sce = (StateChangeEvent) event;

                String type = null;
                String name = null;
                String state = (sce.getState() == StateChangeEvent.Status.STARTED) ? "started"
                        : "stopped";

                if (event instanceof JobStateChangeEvent) {
                    type = "Task"; // we refer to scripts as "tasks" to users.
                    Job job = (Job) sce.getSource();
                    name = job.getScript().getNicename();
                } else if (event instanceof TaskStateChangeEvent) {
                    type = "Transformer";
                    Task task = (Task) sce.getSource();
                    name = task.getTransformerInfo().getNiceName();
                } else {
                    System.err.println(event.getClass().getSimpleName());
                }

                logger.info( ("[STATE] " + type + " " + name + " just "
                        + state));

            } else {
                System.err.println(event.getClass().getSimpleName());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }    
  }
  
  
}

java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.