Exemple #1
0
        };                                                                                                          //Key should be ISO 639-1 values

        static HunspellChecker()
        {
            try
            {
                string dictionaryPath = Hunspell.NativeDllPath;

                spellEngine = new SpellEngine();
                foreach (String lang in languages.Keys)
                {
                    LanguageConfig newConfig = new LanguageConfig();
                    newConfig.LanguageCode     = lang;
                    newConfig.HunspellAffFile  = Path.Combine(dictionaryPath, String.Format("{0}.aff", languages[lang]));
                    newConfig.HunspellDictFile = Path.Combine(dictionaryPath, String.Format("{0}.dic", languages[lang]));
                    newConfig.HunspellKey      = "";
                    newConfig.HyphenDictFile   = Path.Combine(dictionaryPath, String.Format("hyph_{0}.dic", languages[lang]));
                    newConfig.MyThesDatFile    = Path.Combine(dictionaryPath, String.Format("th_{0}_new.dat", languages[lang]));
                    spellEngine.AddLanguage(newConfig);
                }
            }
            catch (Exception ex)
            {
                if (spellEngine != null)
                {
                    spellEngine.Dispose();
                }
                throw new Exception(ex.Message);
            }
        }
Exemple #2
0
 public SpellLevel(int level, string data, SpellEngine engine)
 {
     this.Level = level;
     this.Data = data;
     this.Engine = engine;
     this.LoadLevel();
     this.initSpellType();
 }
Exemple #3
0
 public SpellLevel(int level, string data, SpellEngine engine)
 {
     this.Level  = level;
     this.Data   = data;
     this.Engine = engine;
     this.LoadLevel();
     this.initSpellType();
 }
    // Use this for initialization
    public override void applyAffect(GameObject spell)
    {
        SpellEngine spellEngine = GameObject.FindWithTag("GameController").GetComponent <MasterGameManager>().spellEngine;
        Vector3     oldPos      = spell.transform.localPosition;
        Vector3     newPos      = oldPos + (Vector3.up * ((float)(new System.Random().NextDouble() + 0.1) / 2));
        //GameObject newspell = GameObject.Instantiate(spell, newpos, spell.transform.rotation);
        GameObject newSpell = GameObject.Instantiate(spell, spell.transform.parent);

        newSpell.transform.localPosition = newPos;
        spellEngine.craftedSpells.Add(newSpell);
    }
    // Use this for initialization
    void Awake()
    {
        Application.SetStackTraceLogType(LogType.Log, StackTraceLogType.None);

        spellEngine       = gameObject.GetComponent <SpellEngine>();
        airsigManager     = gameObject.GetComponent <AirSigManager>();
        masterGameManager = GameObject.FindWithTag("GameController").GetComponent <MasterGameManager>();
        // Update the display text
        //textMode.text = string.Format("Mode: {0}", AirSigManager.Mode.DeveloperDefined.ToString());
        //textResult.text = defaultResultText = "Pressing trigger and write symbol in the air\nReleasing trigger when finish";
        //textResult.alignment = TextAnchor.UpperCenter;
        //instruction.SetActive(false);
        //ToggleGestureImage("All");

        // Configure AirSig by specifying target
        developerDefined = new AirSigManager.OnDeveloperDefinedMatch(HandleOnDeveloperDefinedMatch);
        airsigManager.onDeveloperDefinedMatch += developerDefined;
        airsigManager.SetMode(AirSigManager.Mode.DeveloperDefined);
        List <string> temp = new List <string>();

        temp.Add("Dot");
        temp.Add("Line");
        temp.Add("Circle");
        //temp.Add("Square");
        temp.Add("Triangle");

        airsigManager.SetDeveloperDefinedTarget(temp);
        airsigManager.SetClassifier("FinalGestureProfile", "");

        //airsigManager.SetDeveloperDefinedTarget(spellEngine.getCompleteSpellPartsNameList());
        //airsigManager.SetClassifier("GestureProfile1", "");
        //airsigManager.SetClassifier("SpellCoresV1", "");

        /*developerDefinedCore = new AirSigManager.OnDeveloperDefinedMatch(HandleOnDeveloperDefinedMatchCore);
         * airsigManager.onDeveloperDefinedMatch += developerDefinedCore;
         * airsigManager.SetMode(AirSigManager.Mode.DeveloperDefined);
         * airsigManager.SetDeveloperDefinedTarget(spellEngine.getCompleteSpellPartsNameList());
         * airsigManager.SetClassifier("GestureProfile1", "");*/



        //checkDbExist();

        airsigManager.SetTriggerStartKeys(
            AirSigManager.Controller.RIGHT_HAND,
            SteamVR_Controller.ButtonMask.Trigger,
            AirSigManager.PressOrTouch.PRESS);


        airsigManager.SetTriggerStartKeys(
            AirSigManager.Controller.LEFT_HAND,
            SteamVR_Controller.ButtonMask.Touchpad,
            AirSigManager.PressOrTouch.PRESS);
    }
Exemple #6
0
 public SpellDictionary(SpellEngine spellEngine, string localeLang, string dispName)
 {
     engine           = spellEngine;
     locale           = localeLang;
     displayName      = dispName;
     hunspellAffFile  = string.Empty;
     hunspellDictFile = string.Empty;
     hyphenDictFile   = string.Empty;
     myThesIdxFile    = string.Empty;
     myThesDatFile    = string.Empty;
     localeName       = string.Empty;
 }
Exemple #7
0
    void Awake()
    {
        nvrPlayer = GameObject.FindWithTag("Player").GetComponent <NVRPlayer>();

        gestureGameManager                   = GetComponent <GestureGameManager>();
        gestureGameManager.nvrPlayer         = nvrPlayer;
        gestureGameManager.masterGameManager = this;
        assembledSpellQuickBar               = GetComponent <AssembledSpellQuickBar>();

        spellEngine = GetComponent <SpellEngine>();
        spellEngine.masterGameManager = this;
    }
Exemple #8
0
    public void CreationAndDestructionTest()
    {
        SpellEngine engine = new SpellEngine();

        Assert.IsFalse(engine.IsDisposed);

        // Multiple dispose must be allowed
        engine.Dispose();
        Assert.IsTrue(engine.IsDisposed);
        engine.Dispose();
        Assert.IsTrue(engine.IsDisposed);
    }
        public Dictionaries(IEnumerable <string> dictionaryFolders)
        {
            dictFolders = dictionaryFolders;
            dicts       = new List <SpellDictionary>();
            engine      = new SpellEngine();

            KryptonTaskDialog dialog = new KryptonTaskDialog();

            dialog.WindowTitle   = Strings.ErrorLoadDict;
            dialog.CheckboxText  = Strings.IgnoreError;
            dialog.CheckboxState = false;
            dialog.Icon          = MessageBoxIcon.Error;

            foreach (string folder in dictFolders)
            {
                if (!Directory.Exists(folder))
                {
                    continue;
                }

                string[] dictSubFolders = Directory.GetDirectories(folder);
                if (dictSubFolders.Length == 0)
                {
                    ShowErrorLoadDictionary(dialog, folder);
                }
                else
                {
                    foreach (string subFolder in dictSubFolders)
                    {
                        try
                        {
                            LoadDictionary(subFolder);
                            CultureInfo[] cultureinfo = CultureInfo.GetCultures(CultureTypes.AllCultures & ~CultureTypes.NeutralCultures);
                            foreach (CultureInfo info in cultureinfo)
                            {
                                foreach (SpellDictionary dict in dicts)
                                {
                                    if (dict.Locale.ToUpperInvariant() == info.Name.ToUpperInvariant())
                                    {
                                        dict.UpdateLocaleName(info.DisplayName);
                                        break;
                                    }
                                }
                            }
                        }
                        catch (FileNotFoundException)
                        {
                            ShowErrorLoadDictionary(dialog, subFolder);
                        }
                    }
                }
            }
        }
        //=====================================================================

        /// <summary>
        /// Create a global dictionary for the specified culture
        /// </summary>
        /// <param name="culture">The language to use for the dictionary.</param>
        /// <param name="additionalDictionaryFolders">An enumerable list of additional folders to search for
        /// other dictionaries.</param>
        /// <param name="recognizedWords">An optional list of recognized words that will be added to the
        /// dictionary (i.e. from a code analysis dictionary).</param>
        /// <returns>The global dictionary to use or null if one could not be created.</returns>
        public static GlobalDictionary CreateGlobalDictionary(CultureInfo culture,
                                                              IEnumerable <string> additionalDictionaryFolders, IEnumerable <string> recognizedWords)
        {
            GlobalDictionary globalDictionary = null;

            try
            {
                if (globalDictionaries == null)
                {
                    globalDictionaries = new Dictionary <string, GlobalDictionary>();
                }

                if (spellEngine == null)
                {
                    Hunspell.NativeDllPath = Path.Combine(Path.GetDirectoryName(
                                                              Assembly.GetExecutingAssembly().Location), "NHunspell");
                    spellEngine = new SpellEngine();
                }

                // The configuration editor should disallow creating a configuration without at least one
                // language but if someone edits the file manually, they could remove them all.  If that
                // happens, just use the English-US dictionary.
                if (culture == null)
                {
                    culture = new CultureInfo("en-US");
                }

                // If not already loaded, create the dictionary and the thread-safe spell factory instance for
                // the given culture.
                if (!globalDictionaries.TryGetValue(culture.Name, out globalDictionary))
                {
                    globalDictionary = new GlobalDictionary(culture, recognizedWords);

                    // Initialize the dictionaries asynchronously.  We don't care about the result here.
                    _ = Task.Run(() => globalDictionary.InitializeDictionary(additionalDictionaryFolders));

                    globalDictionaries.Add(culture.Name, globalDictionary);
                }
                else
                {
                    // Add recognized words that are not already there
                    globalDictionary.AddRecognizedWords(recognizedWords);
                }
            }
            catch (Exception ex)
            {
                // Ignore exceptions.  Not much we can do, we just won't spell check anything in this language.
                System.Diagnostics.Debug.WriteLine(ex);
            }

            return(globalDictionary);
        }
Exemple #11
0
        /// <summary>
        /// This is called to clear the dictionary cache and dispose of the spelling engine
        /// </summary>
        /// <remarks>This is done whenever a change in solution is detected.  This allows for solution and
        /// project-specific dictionaries to override global dictionaries that may have been in use in a previous
        /// solution.</remarks>
        public static void ClearDictionaryCache()
        {
            if (globalDictionaries != null)
            {
                foreach (var gd in globalDictionaries.Values)
                {
                    gd.Dispose();
                }

                globalDictionaries.Clear();
            }

            if (spellEngine != null)
            {
                spellEngine.Dispose();
                spellEngine = null;
            }
        }
        public ThreadSafeCachedSpellCheckerService()
        {
            this.disposing = false;

            this.spellEngine = new SpellEngine();

            var languageConfig = new LanguageConfig
            {
                LanguageCode     = LanguageCode,
                HunspellAffFile  = Path.Combine(HunspellDictionariesFolder, HunspellAffFile),
                HunspellDictFile = Path.Combine(HunspellDictionariesFolder, HunspellDictFile)
            };

            this.spellEngine.AddLanguage(languageConfig);

            this.spellCache           = new ConcurrentDictionary <string, SpellCheckResponse>();
            this.nonAlphaNumericRegex = new Regex("[^a-zA-Z ]");
        }
    void Awake()
    {
        int[] levelOne = new int[5] {
            3, 0, 0, 0, 0
        };                                             //small, medium, flyer, speed, large
        int[] levelTwo = new int[5] {
            5, 2, 0, 0, 0
        };
        int[] levelThree = new int[5] {
            10, 5, 1, 0, 0
        };
        int[] levelFour = new int[5] {
            13, 10, 5, 3, 0
        };
        int[] levelFive = new int[5] {
            10, 13, 0, 7, 3
        };

        levelPopulation = new int[][] { levelOne, levelTwo, levelThree, levelFour, levelFive };

        nvrPlayer                    = GameObject.FindWithTag("Player").GetComponent <NVRPlayer>();
        gestureGameManager           = GetComponent <GestureGameManager>();
        gestureGameManager.nvrPlayer = nvrPlayer;
        if (GameObject.FindWithTag("tower") != null)
        {
            tower = GameObject.FindWithTag("tower").GetComponent <HumanWatchTower>();
        }

        if (GameObject.FindWithTag("GameController").GetComponentInChildren <PortalSpawning>() != null)
        {
            portalSpawning = GameObject.FindWithTag("GameController").GetComponentInChildren <PortalSpawning>();
            Debug.Log("Portal Spawning object has been found");
        }
        else
        {
            Debug.Log("Portal Spawning object has not been found.");
        }

        gestureGameManager.masterGameManager = this;
        assembledSpellQuickBar = GetComponent <AssembledSpellQuickBar>();

        spellEngine = GetComponent <SpellEngine>();
        spellEngine.masterGameManager = this;
    }
Exemple #14
0
    public void FunctionsTest()
    {
        using (SpellEngine engine = new SpellEngine())
        {
            LanguageConfig enConfig = new LanguageConfig();
            enConfig.LanguageCode     = "en";
            enConfig.HunspellAffFile  = "en_us.aff";
            enConfig.HunspellDictFile = "en_us.dic";
            enConfig.HunspellKey      = "";
            enConfig.HyphenDictFile   = "hyph_en_us.dic";
            enConfig.MyThesDatFile    = "th_en_us_new.dat";
            engine.AddLanguage(enConfig);

            var sp = engine["en"];
            sp.Spell("Hello");
            sp.Suggest("Halo");
            sp.Stem("boys");
            sp.Analyze("boys");
            sp.LookupSynonyms("eingine", true);
            sp.Generate("girl", "boys");

            sp.Spell("Hello");
            sp.Suggest("Halo");
            sp.Stem("boys");
            sp.Analyze("boys");
            sp.LookupSynonyms("eingine", true);
            sp.Generate("girl", "boys");

            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            for (int i = 0; i < 100; ++i)
            {
                sp.Spell("Hello");
                sp.Suggest("girles");
                sp.Stem("boys");
                sp.Analyze("boys");
                sp.LookupSynonyms("eingine", true);
                sp.Generate("girl", "boys");
            }
            stopwatch.Stop();
            Console.WriteLine("Time (ms): " + stopwatch.ElapsedMilliseconds.ToString());
        }
    }
Exemple #15
0
    //public Dictionary<string, SpellComponent> spellComponentName2UnityComponent = new Dictionary<string, SpellComponent>();

    //public bool coreTest = false;
    //public bool elementalAndModiferTest = false;

    // Use this for initialization
    void Start()
    {
        spellEngine = GameObject.FindWithTag("GameController").GetComponent <SpellEngine>();

        /*spellComponentName2UnityComponent.Add("FireV1", new FireElement());
         * spellComponentName2UnityComponent.Add("WaterV1", new WaterElement());
         * spellComponentName2UnityComponent.Add("NatureV1", new NatureElement());
         *
         * spellComponentName2UnityComponent.Add("DamageV1", new DamageModifier());
         * spellComponentName2UnityComponent.Add("SizeV1", new SizeModifier());
         * spellComponentName2UnityComponent.Add("SpeedV1", new SpeedModifier());
         * spellComponentName2UnityComponent.Add("GravityV1", new GravityModifier());
         *
         * spellComponentName2UnityComponent.Add("MultiplierV1", new GravityModifier());
         * spellComponentName2UnityComponent.Add("Add1V1", new GravityModifier());
         * spellComponentName2UnityComponent.Add("PoisonV1", new GravityModifier());
         * spellComponentName2UnityComponent.Add("ExplosionV1", new GravityModifier());
         * spellComponentName2UnityComponent.Add("ParalyzeV1", new GravityModifier());
         * spellComponentName2UnityComponent.Add("SlowV1", new GravityModifier());*/
    }
Exemple #16
0
        public HunspellSpellingPlugin()
        {
            // Set up the spell engine for multi-threaded access.
            SpellEngine = new SpellEngine();

            // Assume we are disabled unless we can configure it properly.
            projectPlugin = new DisabledSpellingProjectPlugin();

            // Figure out the paths to the dictionary files. For the time being,
            // we're going to assume we're using U.S. English.
            string affixFilename;
            string dictionaryFilename;

            if (!GetDictionaryPaths("en_US", out affixFilename, out dictionaryFilename))
            {
                // We couldn't get the dictionary paths, so just stick with the
                // disabled spelling plugin.
                return;
            }

            // Attempt to load the NHunspell plugin. This is a high-quality
            // plugin based on Managed C++. This works nicely in Windows, but
            // has no support for Linux.
            try
            {
                // Attempt to load the U.S. English language. This will throw
                // an exception if it cannot load. If it does, then we use it.
                var englishUnitedStates = new LanguageConfig
                {
                    LanguageCode     = "en_US",
                    HunspellAffFile  = affixFilename,
                    HunspellDictFile = dictionaryFilename,
                    HunspellKey      = string.Empty
                };

                SpellEngine.AddLanguage(englishUnitedStates);

                // If we got this far, set the project plugin to the one that
                // uses the SpellEngine from NHunspell.
                projectPlugin = new SpellEngineSpellingProjectPlugin(this);
                return;
            }
            catch (Exception exception)
            {
                // Report that we can't load the first attempt.
                Console.WriteLine("Cannot load NHunspell: " + exception);
            }

            // If we got this far, we couldn't load the NHunspell plugin.
            // Attempt to load in the PInvoke implementation instead.
            try
            {
                // Create a new Hunspell P/Invoke loader.
                var pinvokePlugin = new PInvokeSpellingProjectPlugin(
                    affixFilename, dictionaryFilename);
                projectPlugin = pinvokePlugin;
            }
            catch (Exception exception)
            {
                // Report that we can't load the first attempt.
                Console.WriteLine("Cannot load NHunspell via P/Invoke: " + exception);
            }
        }
        //=====================================================================

        /// <summary>
        /// Create a global dictionary for the specified culture
        /// </summary>
        /// <param name="culture">The language to use for the dictionary</param>
        /// <returns>The spell factory to use or null if one could not be created</returns>
        public static GlobalDictionary CreateGlobalDictionary(CultureInfo culture)
        {
            GlobalDictionary globalDictionary = null;
            string           affixFile, dictionaryFile;

            try
            {
                if (globalDictionaries == null)
                {
                    globalDictionaries = new Dictionary <string, GlobalDictionary>();
                }

                // If no culture is specified, use the default culture
                if (culture == null)
                {
                    culture = SpellCheckerConfiguration.DefaultLanguage;
                }

                // If not already loaded, create the dictionary and the thread-safe spell factory instance for
                // the given culture.
                if (!globalDictionaries.ContainsKey(culture.Name))
                {
                    string dllPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                                                  "NHunspell");

                    if (spellEngine == null)
                    {
                        Hunspell.NativeDllPath = dllPath;
                        spellEngine            = new SpellEngine();
                    }

                    // Look in the configuration folder first for user-supplied dictionaries
                    affixFile = Path.Combine(SpellCheckerConfiguration.ConfigurationFilePath,
                                             culture.Name + ".aff");
                    dictionaryFile = Path.ChangeExtension(affixFile, ".dic");

                    // Dictionary file names may use a dash or an underscore as the separator.  Try both ways
                    // in case they aren't named consistently which does happen.
                    if (!File.Exists(affixFile))
                    {
                        affixFile = Path.Combine(SpellCheckerConfiguration.ConfigurationFilePath,
                                                 culture.Name.Replace('-', '_') + ".aff");
                    }

                    if (!File.Exists(dictionaryFile))
                    {
                        dictionaryFile = Path.Combine(SpellCheckerConfiguration.ConfigurationFilePath,
                                                      culture.Name.Replace('-', '_') + ".dic");
                    }

                    // If not found, default to the English dictionary supplied with the package.  This can at
                    // least clue us in that it didn't find the language-specific dictionary when the suggestions
                    // are in English.
                    if (!File.Exists(affixFile) || !File.Exists(dictionaryFile))
                    {
                        affixFile      = Path.Combine(dllPath, "en_US.aff");
                        dictionaryFile = Path.ChangeExtension(affixFile, ".dic");
                    }

                    spellEngine.AddLanguage(new LanguageConfig
                    {
                        LanguageCode     = culture.Name,
                        HunspellAffFile  = affixFile,
                        HunspellDictFile = dictionaryFile
                    });

                    globalDictionaries.Add(culture.Name, new GlobalDictionary(culture, spellEngine[culture.Name]));
                }

                globalDictionary = globalDictionaries[culture.Name];
            }
            catch (Exception ex)
            {
                // Ignore exceptions.  Not much we can do, we'll just not spell check anything.
                System.Diagnostics.Debug.WriteLine(ex);
            }

            return(globalDictionary);
        }
Exemple #18
0
        //=====================================================================

        /// <summary>
        /// Create a global dictionary for the specified culture
        /// </summary>
        /// <param name="culture">The language to use for the dictionary</param>
        /// <returns>The spell factory to use or null if one could not be created</returns>
        public static GlobalDictionary CreateGlobalDictionary(CultureInfo culture)
        {
            GlobalDictionary globalDictionary = null;

            try
            {
                if (globalDictionaries == null)
                {
                    globalDictionaries = new Dictionary <string, GlobalDictionary>();
                }

                // If no culture is specified, use the default culture
                if (culture == null)
                {
                    culture = SpellCheckerConfiguration.DefaultLanguage;
                }

                // If not already loaded, create the dictionary and the thread-safe spell factory instance for
                // the given culture.
                if (!globalDictionaries.ContainsKey(culture.Name))
                {
                    string dllPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

                    if (spellEngine == null)
                    {
                        Hunspell.NativeDllPath = dllPath;
                        spellEngine            = new SpellEngine();
                    }

                    // Look in the configuration folder first for user-supplied dictionaries
                    string dictionaryFile = Path.Combine(SpellCheckerConfiguration.ConfigurationFilePath,
                                                         culture.Name.Replace("-", "_") + ".aff");

                    // If not found, default to the English dictionary supplied with the package.  This can at
                    // least clue us in that it didn't find the language-specific dictionary when the suggestions
                    // are in English.
                    if (!File.Exists(dictionaryFile))
                    {
                        dictionaryFile = Path.Combine(dllPath, "Spelling", "en_US.aff");
                    }

                    LanguageConfig lc = new LanguageConfig();
                    lc.LanguageCode     = culture.Name;
                    lc.HunspellAffFile  = dictionaryFile;
                    lc.HunspellDictFile = Path.ChangeExtension(dictionaryFile, ".dic");

                    spellEngine.AddLanguage(lc);

                    globalDictionaries.Add(culture.Name, new GlobalDictionary(culture,
                                                                              spellEngine[culture.Name]));
                }

                globalDictionary = globalDictionaries[culture.Name];
            }
            catch (Exception ex)
            {
                // Ignore exceptions.  Not much we can do, we'll just not spell check anything.
                System.Diagnostics.Debug.WriteLine(ex);
            }

            return(globalDictionary);
        }
Exemple #19
0
        static SpellEngineManager()
        {
            try
            {
                Languages       = new List <string>();
                AlphabetLetters = new Dictionary <string, List <char> >();

                string dictionaryPath = new DirectoryInfo(Hunspell.NativeDllPath).Parent.FullName + "\\dicts";

                DirectoryInfo   di          = new DirectoryInfo(dictionaryPath);
                FileInfo[]      files       = di.GetFiles("*", SearchOption.AllDirectories);
                List <FileInfo> allAffFiles = files.Where(f => f.FullName.EndsWith(".aff", StringComparison.InvariantCultureIgnoreCase)).OrderBy(f => f.Name).ToList();
                AllAffFiles = allAffFiles;
                List <FileInfo> allDicFiles = files.Where(f => f.FullName.EndsWith(".dic", StringComparison.InvariantCultureIgnoreCase)).OrderBy(f => f.Name).ToList();
                AllDicFiles = allDicFiles;


                SpellEngine = new SpellEngine();

                foreach (FileInfo affFile in allAffFiles)
                {
                    try
                    {
                        //affFile.Directory.Parent.Name

                        string nameWithoutExtension = affFile.Directory.Name.ToLower();// affFile.Name.Replace(".aff", string.Empty).ToLowerInvariant();

                        LanguageConfig enConfig = new LanguageConfig();
                        enConfig.LanguageCode     = nameWithoutExtension;
                        enConfig.HunspellAffFile  = affFile.FullName;
                        enConfig.HunspellDictFile = affFile.FullName.Replace(".aff", ".dic");
                        enConfig.HunspellKey      = "";
                        //SpellEngine.AddLanguage(enConfig);
                        //var alphabetChars = GetAlphabetLetters(enConfig.HunspellAffFile);
                        //AlphabetLetters[nameWithoutExtension] = alphabetChars;
                        Languages.Add(nameWithoutExtension);
                    }
                    catch (Exception ex)
                    {
                    }
                }



                //SpellEngine = new SpellEngine();
                //LanguageConfig enConfig = new LanguageConfig();
                //enConfig.LanguageCode = "en";
                //enConfig.HunspellAffFile = files.FirstOrDefault(f => f.FullName.EndsWith("en_us.aff", StringComparison.InvariantCultureIgnoreCase)).FullName; //Path.Combine(dictionaryPath, "en_us.aff");
                //enConfig.HunspellDictFile = files.FirstOrDefault(f => f.FullName.EndsWith("en_us.dic", StringComparison.InvariantCultureIgnoreCase)).FullName; //Path.Combine(dictionaryPath, "en_us.dic");
                //enConfig.HunspellKey = "";
                //SpellEngine.AddLanguage(enConfig);
                //AlphabetLetters["en"] = GetAlphabetLetters(enConfig.HunspellAffFile);


                //enConfig = new LanguageConfig();
                //enConfig.LanguageCode = "bg";
                //enConfig.HunspellAffFile = files.FirstOrDefault(f => f.FullName.EndsWith("bg.aff", StringComparison.InvariantCultureIgnoreCase)).FullName; //Path.Combine(dictionaryPath, "en_us.aff");
                //enConfig.HunspellDictFile = files.FirstOrDefault(f => f.FullName.EndsWith("bg.dic", StringComparison.InvariantCultureIgnoreCase)).FullName; //Path.Combine(dictionaryPath, "en_us.dic");
                //enConfig.HunspellKey = "";
                //SpellEngine.AddLanguage(enConfig);
                //AlphabetLetters["bg"] = GetAlphabetLetters(enConfig.HunspellAffFile);
            }
            catch (Exception)
            {
                if (SpellEngine != null)
                {
                    SpellEngine.Dispose();
                }

                throw;
            }
        }
Exemple #20
0
 // Use this for initialization
 void Awake()
 {
     spellEngine = GameObject.FindWithTag("GameController").GetComponent <SpellEngine>();
     gameManager = GameObject.FindWithTag("GameController").GetComponent <MasterGameManager>();
 }
Exemple #21
0
 public SpellEffect(SpellEngine engine, string data)
 {
     this.Engine = engine;
     this.Data   = data;
     this.LoadEffect();
 }
Exemple #22
0
        public ActionResult SpellText(string htmlEncoded, string text, string langugage)
        {
            FileInfo affFile = SpellEngineManager.AllAffFiles.FirstOrDefault(f => f.Directory.Name.Equals(langugage, StringComparison.InvariantCultureIgnoreCase));
            string   nameWithoutExtension = affFile.Directory.Name.ToLower();// affFile.Name.Replace(".aff", string.Empty).ToLowerInvariant();

            using (SpellEngine spellEngine = new SpellEngine())
            {
                LanguageConfig enConfig = new LanguageConfig();
                enConfig.LanguageCode     = nameWithoutExtension;
                enConfig.HunspellAffFile  = affFile.FullName;
                enConfig.HunspellDictFile = affFile.FullName.Replace(".aff", ".dic");
                enConfig.HunspellKey      = "";
                spellEngine.AddLanguage(enConfig);
                var alphabetCharsOld = SpellEngineManager.GetAlphabetLetters(enConfig.HunspellAffFile);
                SpellEngineManager.AlphabetLetters[nameWithoutExtension] = alphabetCharsOld;



                string html = Server.HtmlDecode(htmlEncoded);

                //HtmlDocument doc = new HtmlDocument();
                //doc.LoadHtml(html);
                ////doc.Save(Console.Out); // show before
                //RemoveComments(doc.DocumentNode);
                //var test = doc.DocumentNode.InnerHtml;



                //?? test
                //var indexOfBase = html.IndexOf("<base");
                //if (indexOfBase > 0)
                //{
                //    html = html.Substring(indexOfBase);
                //    html = html.Replace("</body>", string.Empty);
                //    html = html.Replace("</html>", string.Empty);

                //}


                var testForClearText = StripTagsCharArray(html);
                // ?? test
                text = testForClearText;

                var           chars      = text.ToCharArray();
                List <string> emptyChars = new List <string>();
                foreach (char c in chars)
                {
                    if (string.IsNullOrWhiteSpace(c.ToString()))
                    {
                        emptyChars.Add(c.ToString());
                    }
                }
                emptyChars = emptyChars.Distinct().ToList();

                var alphabetChars = SpellEngineManager.AlphabetLetters[langugage];

                //var punctuationChars = chars.Where(c => char.IsPunctuation(c)).Distinct().ToList();
                var nonAlphabetChars = chars.Distinct().Except(alphabetChars).ToList();
                //var nonAlphabetChars = chars.Distinct().Except(alphabetChars).Except(punctuationChars).ToList();

                //for (int i = 0; i < punctuationChars.Count; i++)
                //{
                //    text = text.Replace(punctuationChars[i].ToString(), " ");
                //}

                //var words = text.Replace("\n", " ").Replace(",", " ").Replace(".", " ").Split(emptyChars.ToArray(), StringSplitOptions.RemoveEmptyEntries).ToList();
                var words = text.Split(emptyChars.ToArray(), StringSplitOptions.RemoveEmptyEntries).ToList();



                //var words = text.Replace("\n", " ").Replace(",", " ").Replace(".", " ").Split(emptyChars.ToArray(), StringSplitOptions.RemoveEmptyEntries).ToList();
                List <string> wrongWords = new List <string>();

                //words = words.Select(w => w.Trim()).Where(s => !string.IsNullOrWhiteSpace(s)).Where(w => ContainsLetters(w)).ToList();
                words = words.Select(w => w.Trim()).Where(s => !string.IsNullOrWhiteSpace(s)).Where(w => ContainsOnlyAlphabetLetters(w, alphabetChars)).ToList();

                foreach (string word in words)
                {
                    var res = spellEngine[langugage].Spell(word);
                    if (!res)
                    {
                        wrongWords.Add(word);
                    }
                }
                wrongWords = wrongWords.Distinct().ToList();

                StringBuilder sbSummary = new StringBuilder();
                string        begin     = @"  <table id='grid'>
                <colgroup>
                    <col />
                    <col />                    
                </colgroup>
                <thead>
                    <tr>
                        <th data-field='make'>Word</th>
                        <th data-field='model'>Suggestion</th>                        
                    </tr>
                </thead>
                <tbody>";
                sbSummary.Append(begin);

                foreach (string word in wrongWords)
                {
                    var           suggest = spellEngine[langugage].Suggest(word);
                    StringBuilder sb      = new StringBuilder();
                    foreach (var item in suggest)
                    {
                        sb.Append(item + ", ");
                    }
                    string suggestions = sb.ToString();


                    //var wordsInHtml = html.Split(emptyChars.ToArray(), StringSplitOptions.None);
                    //StringBuilder newHtml = new StringBuilder();
                    //for (int i = 0; i < wordsInHtml.Count(); i++)
                    //{
                    //    var currWord = wordsInHtml[i];
                    //    if (currWord.Trim() == word.Trim())
                    //    {
                    //        newHtml.Append($"<span title='{suggestions}' style='color:blueviolet;background-color:yellow'>{word}</span>");
                    //    }
                    //    else
                    //    {
                    //        newHtml.Append(currWord);
                    //    }
                    //}

                    //html = newHtml.ToString();

                    // заради Angstriom го правя това - съдържа не само букви
                    //if (word.ToCharArray().All(c => char.IsLetter(c)))
                    {
                        string input   = html;
                        string pattern = $@"\b{word}\b";
                        string replace = $"<span title='{suggestions}' style='color:blueviolet;background-color:yellow'>{word}</span>";
                        var    newhtml = Regex.Replace(input, pattern, replace);
                        if (newhtml != html)
                        {
                            // за да няма в грида повече думи отколкото сме подчертали в editor
                            sbSummary.Append(CreateGridRow(word, suggestions));
                        }
                        html = newhtml;
                    }


                    //html = html.Replace(word, $"<span title='{suggestions}' style='color:blueviolet;background-color:yellow'>{word}</span>");
                }

                sbSummary.Append("</tbody></table>");

                var returnObject = new { html = html + "<div></div>", summary = sbSummary.ToString() };
                return(Json(returnObject));
            }
        }
Exemple #23
0
        private void btCorrectIt_Click(object sender, EventArgs e)
        {
            if (cbMethod.SelectedItem.ToString() == "-- Choose method --")
            {
                MessageBox.Show("Choose method first", "", MessageBoxButtons.OK);
                return;
            }
            if (!File.Exists(txOCR.Text.Trim()))
            {
                MessageBox.Show("Browse file first", "", MessageBoxButtons.OK);
                return;
            }

            ResetControls(false);

            articleFile = txOCR.Text.Trim();
            Correction correction = new Correction();
            Stemmer    stemmer    = new Stemmer();

            // DeHyphenate and clean text:
            string dehyphenatedText = correction.DeHyphenate(articleFile);

            rtbOCR.Text = dehyphenatedText;

            // for analysis:
            string dehyphenatedTextGT = "";

            if (File.Exists(articleFile.Substring(0, articleFile.Length - 4) + "GT.txt"))
            {
                articleFileGT = articleFile.Substring(0, articleFile.Length - 4) + "GT.txt";
            }
            articleFileName = Path.GetFileName(articleFile);
            if (!string.IsNullOrEmpty(articleFileGT))
            {
                dehyphenatedTextGT = correction.DeHyphenate(articleFileGT);
            }

            // tokenize:
            deHyphenateTokens = correction.GetTokensFromText(dehyphenatedText);

            Regex rgx = new Regex("[^a-zA-Z]"); //omit all non alphabet word And clean word from non alphabet:

            // for analysis:
            Dictionary <int, string> deHyphenateTokensGT = new Dictionary <int, string>();

            if (!string.IsNullOrEmpty(articleFileGT))
            {
                deHyphenateTokensGT = correction.GetTokensFromText(dehyphenatedTextGT);
                foreach (KeyValuePair <int, string> token in deHyphenateTokens)
                {
                    correction.InsertOCRAndTruth(articleFileName, token.Key, rgx.Replace(token.Value, ""), rgx.Replace(deHyphenateTokensGT[token.Key], ""));
                }
            }

            // Omit non character,single char, All Capitals word, and clean word from non alphabet:
            var tmp = deHyphenateTokens.Where(p => p.Value.Length > 1).ToDictionary(p => p.Key, p => p.Value);

            tmp = tmp.Where(p => p.Value.Any(Char.IsLetter)).ToDictionary(p => p.Key, p => rgx.Replace(p.Value, ""));
            Dictionary <int, string> cleanTokens = tmp.Where(p => !p.Value.All(Char.IsUpper)).ToDictionary(p => p.Key, p => p.Value);



            // Find Suggestion:
            if (cbMethod.SelectedItem.ToString().EndsWith("Hunspell"))
            {
                string hunspellLog = "";
                // find Suggestion using Hunspell:
                foreach (KeyValuePair <int, string> err in cleanTokens)
                {
                    string        errInNewSpell       = correction.ChangeOldToNewSpell(err.Value).ToLowerInvariant();
                    List <string> hunspellSuggestions = new List <string>();
                    using (SpellEngine engine = new SpellEngine())
                    {
                        LanguageConfig idConfig = new LanguageConfig();
                        idConfig.LanguageCode     = "id";
                        idConfig.HunspellAffFile  = "id_ID.aff";
                        idConfig.HunspellDictFile = "id_ID.dic";
                        idConfig.HunspellKey      = "";
                        engine.AddLanguage(idConfig);
                        bool correct = engine["id"].Spell(errInNewSpell);
                        if (!correct)
                        {
                            hunspellSuggestions = engine["id"].Suggest(errInNewSpell);
                            if (hunspellSuggestions.Count > 0 && err.Value != correction.ChangeNewToOldSpell(hunspellSuggestions[0]))
                            {
                                deHyphenateTokens[err.Key] = "[" + correction.ChangeNewToOldSpell(hunspellSuggestions[0]) + "]";
                            }
                            // for analysis:
                            if (!string.IsNullOrEmpty(articleFileGT))
                            {
                                correction.UpdateFields(articleFileName, err.Key, new Dictionary <string, string> {
                                    { getFieldNameFromOption(), rgx.Replace(deHyphenateTokens[err.Key], "") }, { getFieldNameFromOption().Replace("Correction", "Log"), hunspellLog }
                                });
                            }
                        }
                        else
                        {
                            // for analysis:
                            if (!string.IsNullOrEmpty(articleFileGT))
                            {
                                correction.UpdateFields(articleFileName, err.Key, new Dictionary <string, string> {
                                    { getFieldNameFromOption(), err.Value }, { getFieldNameFromOption().Replace("Correction", "Log"), err.Value + " is correct" }
                                });
                            }
                        }
                    }
                }
                ResetControls(true);
                return;
            }


            //check only unique word (assumption:duplicate word is correct word) :
            Dictionary <int, string> checkTokens = cleanTokens;
            var duplicateValues = checkTokens.GroupBy(x => x.Value).Where(x => x.Count() > 1);

            List <int> duplicateKeys = new List <int>();

            foreach (var item in checkTokens)
            {
                foreach (var dup in duplicateValues)
                {
                    if (item.Value == dup.Key)
                    {
                        duplicateKeys.Add(item.Key);
                    }
                }
            }
            foreach (var dupkey in duplicateKeys)
            {
                // for analysis
                if (!string.IsNullOrEmpty(articleFileGT))
                {
                    correction.UpdateFields(articleFileName, dupkey, new Dictionary <string, string> {
                        { "NCorrection", checkTokens[dupkey] }, { "NLog", "Duplicate" }, { "Correction", checkTokens[dupkey] }, { "Log", "Duplicate" }, { "WOSearchCorrection", checkTokens[dupkey] }, { "WOSearchLog", "Duplicate" }, { "WOStemCorrection", checkTokens[dupkey] }, { "WOStemLog", "Duplicate" }, { "WOStemSearchCorrection", checkTokens[dupkey] }, { "WOStemSearchLog", "Duplicate" }, { "GooglePureCorrection", checkTokens[dupkey] }, { "GooglePureLog", "Duplicate" }
                    });
                }
                checkTokens.Remove(dupkey);
            }


            //Check Word using Dictionary(kbbi+kompas pilihan, entitas kota,negara, nama pahlawan dari wiki ):
            errors = new Dictionary <int, string>();
            foreach (KeyValuePair <int, string> token in checkTokens)
            {
                // change Soewandi to Modern Spelling:
                string wordToCheck = correction.ChangeOldToNewSpell(token.Value).ToLowerInvariant();

                // check word in Dictionary and Add to Error list if not there:
                int frequency;
                if (!correction.CheckUnigram(wordToCheck, getSQLQueryToCheckUnigram(), out frequency))
                {
                    if (cbMethod.SelectedItem.ToString().Contains("Stemmer"))
                    {
                        // check again its stem in dictionary :
                        string stem = stemmer.Stemming(wordToCheck);
                        if (wordToCheck != stem && stemmer.checkStem(stem))
                        {
                            // for analysis
                            if (!string.IsNullOrEmpty(articleFileGT))
                            {
                                correction.UpdateFields(articleFileName, token.Key, new Dictionary <string, string> {
                                    { getFieldNameFromOption(), token.Value }, { getFieldNameFromOption().Replace("Correction", "Log"), stem + " is word" }
                                });
                            }
                        }
                        else // jika tidak ada di kamus:
                        {
                            errors.Add(token.Key, wordToCheck);
                        }
                    }
                    else
                    {
                        errors.Add(token.Key, wordToCheck);
                    }
                }
                else // jika ada di kamus:
                {
                    // for analysis
                    if (!string.IsNullOrEmpty(articleFileGT))
                    {
                        correction.UpdateFields(articleFileName, token.Key, new Dictionary <string, string> {
                            { getFieldNameFromOption(), token.Value }, { getFieldNameFromOption().Replace("Correction", "Log"), wordToCheck + " is correct" }
                        });
                    }
                }
            }


            // Find Suggestion:
            if (cbMethod.SelectedItem.ToString().EndsWith("Google"))
            {
                timerGoogle.Enabled = true;
                indexTimerGoogle    = 0;
                return;
            }
            else
            {
                foreach (KeyValuePair <int, string> err in errors)
                {
                    //get suggestion:
                    string log; string suggestion;
                    suggestion = correction.GetSuggestion(getSPNameForGetCandidates(), deHyphenateTokens, err.Key, err.Value, out log, getWithStemAndAffixCorrParamFromOption(), getWithSearchParamFromOption());

                    // Change suggestion back to Old Spell if any suggestions:
                    if (log != "No candidates")
                    {
                        suggestion = correction.ChangeNewToOldSpell(suggestion);
                    }

                    // update token dic with suggestion:
                    if (!suggestion.Equals(deHyphenateTokens[err.Key], StringComparison.OrdinalIgnoreCase))
                    {
                        deHyphenateTokens[err.Key] = "[" + suggestion + "]";
                    }

                    // for analysis:
                    if (!string.IsNullOrEmpty(articleFileGT))
                    {
                        correction.UpdateFields(articleFileName, err.Key, new Dictionary <string, string> {
                            { getFieldNameFromOption(), suggestion }, { getFieldNameFromOption().Replace("Correction", "Log"), log }
                        });
                    }
                }
                ResetControls(true);
            }
        }
Exemple #24
0
 // Update is called once per frame
 void Start()
 {
     assembledSpellQuickBar = GameObject.FindWithTag("GameController").GetComponent <AssembledSpellQuickBar>();
     spellEngine            = GameObject.FindWithTag("GameController").GetComponent <SpellEngine>();
 }
Exemple #25
0
 public SpellEffect(SpellEngine engine, string data)
 {
     this.Engine = engine;
     this.Data = data;
     this.LoadEffect();
 }
Exemple #26
0
        //=====================================================================

        /// <summary>
        /// Create a global dictionary for the specified culture
        /// </summary>
        /// <param name="culture">The language to use for the dictionary.</param>
        /// <param name="serviceProvider">A service provider used to interact with the solution/project</param>
        /// <param name="additionalDictionaryFolders">An enumerable list of additional folders to search for
        /// other dictionaries.</param>
        /// <param name="recognizedWords">An optional list of recognized words that will be added to the
        /// dictionary (i.e. from a code analysis dictionary).</param>
        /// <returns>The global dictionary to use or null if one could not be created.</returns>
        public static GlobalDictionary CreateGlobalDictionary(CultureInfo culture, IServiceProvider serviceProvider,
                                                              IEnumerable <string> additionalDictionaryFolders, IEnumerable <string> recognizedWords)
        {
            GlobalDictionary globalDictionary = null;
            string           affixFile, dictionaryFile, userWordsFile;

            try
            {
                // The configuration editor should disallow creating a configuration without at least one
                // language but if someone edits the file manually, they could remove them all.  If that
                // happens, just use the English-US dictionary.
                if (culture == null)
                {
                    culture = new CultureInfo("en-US");
                }

                if (globalDictionaries == null)
                {
                    globalDictionaries = new Dictionary <string, GlobalDictionary>();
                }

                // If not already loaded, create the dictionary and the thread-safe spell factory instance for
                // the given culture.
                if (!globalDictionaries.ContainsKey(culture.Name))
                {
                    string dllPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                                                  "NHunspell");

                    if (spellEngine == null)
                    {
                        Hunspell.NativeDllPath = dllPath;
                        spellEngine            = new SpellEngine();
                    }

                    // Look for all available dictionaries and get the one for the requested culture
                    var dictionaries = SpellCheckerDictionary.AvailableDictionaries(additionalDictionaryFolders);
                    SpellCheckerDictionary userDictionary;

                    if (dictionaries.TryGetValue(culture.Name, out userDictionary))
                    {
                        affixFile      = userDictionary.AffixFilePath;
                        dictionaryFile = userDictionary.DictionaryFilePath;
                        userWordsFile  = userDictionary.UserDictionaryFilePath;
                    }
                    else
                    {
                        affixFile = dictionaryFile = userWordsFile = null;
                    }

                    // If not found, default to the English dictionary supplied with the package.  This can at
                    // least clue us in that it didn't find the language-specific dictionary when the suggestions
                    // are in English.
                    if (affixFile == null || dictionaryFile == null || !File.Exists(affixFile) ||
                        !File.Exists(dictionaryFile))
                    {
                        affixFile      = Path.Combine(dllPath, "en_US.aff");
                        dictionaryFile = Path.ChangeExtension(affixFile, ".dic");
                        userWordsFile  = Path.Combine(SpellingConfigurationFile.GlobalConfigurationFilePath,
                                                      "en-US_User.dic");
                    }

                    spellEngine.AddLanguage(new LanguageConfig
                    {
                        LanguageCode     = culture.Name,
                        HunspellAffFile  = affixFile,
                        HunspellDictFile = dictionaryFile
                    });

                    globalDictionaries.Add(culture.Name, new GlobalDictionary(culture, spellEngine[culture.Name],
                                                                              dictionaryFile, userWordsFile, serviceProvider));
                }

                globalDictionary = globalDictionaries[culture.Name];

                // Add recognized words that are not already there
                globalDictionary.AddRecognizedWords(recognizedWords);
            }
            catch (Exception ex)
            {
                // Ignore exceptions.  Not much we can do, we just won't spell check anything.
                System.Diagnostics.Debug.WriteLine(ex);
            }

            return(globalDictionary);
        }