public static string GetField(string bibtex, string field)
 {
     try
     {
         BibTexItem bibtex_item = BibTexParser.ParseOne(bibtex, false);
         return(GetField(bibtex_item, field));
     }
     catch (Exception ex)
     {
         Logging.Warn(ex, "There was a problem extracting from the BibTeX");
         return("");
     }
 }
        public static bool DoesBibTeXMatchDocument(string bibtex, PDFDocument pdf_document, out PDFSearchResultSet search_result_set)
        {
            try
            {
                if (!String.IsNullOrEmpty(bibtex))
                {
                    BibTexItem bibtex_item = BibTexParser.ParseOne(bibtex, true);

                    return(DoesBibTeXMatchDocument(bibtex_item, pdf_document, out search_result_set));
                }
            }
            catch (Exception) { }

            search_result_set = new PDFSearchResultSet();
            return(false);
        }
        private void ButtonApplyBibTeX_Click(object sender, RoutedEventArgs e)
        {
            List <PDFDocument> selected_pdf_documents = SelectedPDFDocuments;

            if (null == selected_pdf_documents)
            {
                return;
            }

            if (!MessageBoxes.AskQuestion("Are you sure you want to mass-edit {0} documents?", selected_pdf_documents.Count))
            {
                return;
            }

            BibTexItem bibtex_item_global = BibTexParser.ParseOne(bibtex_stub.BibTex, true);

            int non_updateable_documents = 0;

            foreach (var pdf_document in selected_pdf_documents)
            {
                BibTexItem bibtex_item = pdf_document.BibTexItem;
                if (null != bibtex_item)
                {
                    if (!String.IsNullOrEmpty(bibtex_item_global.Type))
                    {
                        bibtex_item.Type = bibtex_item_global.Type;
                    }

                    foreach (var field_pair in bibtex_item_global.Fields)
                    {
                        bibtex_item[field_pair.Key] = field_pair.Value;
                    }

                    pdf_document.BibTex = bibtex_item.ToBibTex();
                    pdf_document.Bindable.NotifyPropertyChanged(() => pdf_document.BibTex);
                }
                else
                {
                    ++non_updateable_documents;
                }
            }

            if (0 < non_updateable_documents)
            {
                MessageBoxes.Warn("There was a problem updating {0} documents as they do not have an existing BibTeX record associated with them.", non_updateable_documents);
            }
        }
        // ----------------------------------------------------------------------------------------

        public static void Test()
        {
            string sample_bibtext = @"@conference{kamp1984theory,title =       {{A theory of truth and semantic representation}},author =       {Kamp, H.},booktitle={Truth, Interpretation and Information: Selected Papers from the Third Amsterdam Colloquium},pages={1--41},year={1984}";

            Logging.Info("BibTex is:\n" + sample_bibtext);

            BibTexItem bibtex_item = BibTexParser.ParseOne(sample_bibtext, false);

            Logging.Info("Title is: " + GetTitle(bibtex_item));
            Logging.Info("Author is: " + GetAuthor(bibtex_item));
            Logging.Info("Year is: " + GetYear(bibtex_item));

            string replaced_bibtex = sample_bibtext;

            replaced_bibtex = SetTitle(replaced_bibtex, "New title");
            replaced_bibtex = SetAuthor(replaced_bibtex, "New author");
            replaced_bibtex = SetYear(replaced_bibtex, "New year");

            Logging.Info("Replaced BibTex is:\n" + replaced_bibtex);
        }
        void RebuidTextAndGrid()
        {
            string bibtex = BibTeX;

            if (String.IsNullOrEmpty(bibtex) && !ForceHideNoBibTeXInstructions)
            {
                ObjNoBibTeXInstructions.Visibility = Visibility.Visible;
            }
            else
            {
                ObjNoBibTeXInstructions.Visibility = Visibility.Collapsed;
            }

            BibTexItem bibtex_item = BibTexParser.ParseOne(bibtex, true);

            if (null == bibtex_item)
            {
                bibtex_item = new BibTexItem();
            }

            // If there were any exceptions, go pink and jump to the text editor
            if (bibtex_item.Exceptions.Count > 0 || bibtex_item.Warnings.Count > 0)
            {
                TextBlock tb = new TextBlock();
                tb.FontFamily   = new FontFamily("Courier New");
                tb.Text         = bibtex_item.GetExceptionsAndMessagesString();
                tb.TextWrapping = TextWrapping.Wrap;
                tb.MaxWidth     = 400;

                ImageBibTeXParseError.ToolTip    = tb;
                ImageBibTeXParseError.Visibility = ObjErrorPanel.Visibility = Visibility.Visible;
            }
            else
            {
                ObjErrorPanel.ToolTip            = null;
                ImageBibTeXParseError.Visibility = ObjErrorPanel.Visibility = Visibility.Collapsed;
            }

            BuildGridFromBibTeX(bibtex, bibtex_item);
            BuildTextFromBibTeX(bibtex, bibtex_item);
        }
 /// <summary>
 /// After setting the field, returns the WHOLE bibtex again
 /// </summary>
 /// <param name="bibtex"></param>
 /// <param name="field"></param>
 /// <param name="field_value"></param>
 /// <returns></returns>
 public static string SetField(string bibtex, string field, string field_value)
 {
     try
     {
         BibTexItem item = BibTexParser.ParseOne(bibtex, false);
         if (null != item)
         {
             item[field] = field_value;
             return(item.ToBibTex());
         }
         else
         {
             return(bibtex);
         }
     }
     catch (Exception ex)
     {
         Logging.Warn(ex, "There was a problem setting the BibTeX");
         return(null);
     }
 }
Example #7
0
        internal static void Export(WebLibraryDetail web_library_detail, List <PDFDocument> pdf_documents, string base_path, Dictionary <string, PDFDocumentExportItem> pdf_document_export_items)
        {
            Logging.Info("Exporting entries to BibTeXTAB separated");

            // First work out what fields are available
            List <string> field_names = null;
            {
                HashSet <string> field_names_set = new HashSet <string>();
                for (int i = 0; i < pdf_documents.Count; ++i)
                {
                    PDFDocument pdf_document = pdf_documents[i];
                    if (!String.IsNullOrEmpty(pdf_document.BibTex))
                    {
                        BibTexItem item = BibTexParser.ParseOne(pdf_document.BibTex, true);
                        if (null != item)
                        {
                            foreach (var field in item.Fields)
                            {
                                field_names_set.Add(field.Key.ToLower());
                            }
                        }
                    }
                }

                field_names = new List <string>(field_names_set);
                field_names.Sort();
            }

            // Write out the header
            DateTime      now = DateTime.Now;
            StringBuilder sb  = new StringBuilder();

            sb.AppendLine("% -------------------------------------------------------------------------");
            sb.AppendLine(String.Format("% This tab separated file was generated by Qiqqa ({0}?ref=EXPTAB)", Common.Configuration.WebsiteAccess.Url_Documentation4Qiqqa));
            sb.AppendLine(String.Format("% {0} {1}", now.ToLongDateString(), now.ToLongTimeString()));
            sb.AppendLine("% Version 1");
            sb.AppendLine("% -------------------------------------------------------------------------");
            sb.AppendLine();

            // Headers
            sb.AppendFormat("{0}\t", "Fingerprint");
            sb.AppendFormat("{0}\t", "Filename");
            sb.AppendFormat("{0}\t", "BibTexKey");
            sb.AppendFormat("{0}\t", "BibTexType");
            foreach (string field_name in field_names)
            {
                sb.AppendFormat("{0}\t", FormatFreeText(field_name));
            }
            sb.AppendLine();

            // Write out the entries
            for (int i = 0; i < pdf_documents.Count; ++i)
            {
                StatusManager.Instance.UpdateStatus("TabExport", String.Format("Exporting entry {0} of {1}", i, pdf_documents.Count), i, pdf_documents.Count);

                PDFDocument pdf_document = pdf_documents[i];
                sb.AppendFormat("{0}\t", pdf_document.Fingerprint);
                sb.AppendFormat("{0}\t", pdf_document_export_items.ContainsKey(pdf_document.Fingerprint) ? pdf_document_export_items[pdf_document.Fingerprint].filename : "");

                try
                {
                    if (!String.IsNullOrEmpty(pdf_document.BibTex))
                    {
                        BibTexItem item = BibTexParser.ParseOne(pdf_document.BibTex, true);
                        if (null != item)
                        {
                            sb.AppendFormat("{0}\t", item.Key);
                            sb.AppendFormat("{0}\t", item.Type);
                            foreach (string field_name in field_names)
                            {
                                sb.AppendFormat("{0}\t", item.ContainsField(field_name) ? FormatFreeText(item[field_name]) : "");
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logging.Error(ex, "There was a problem exporting the tab representation for document {0}", pdf_document.Fingerprint);
                }

                sb.AppendLine();
            }

            // Write to disk
            string filename = Path.GetFullPath(Path.Combine(base_path, @"Qiqqa.BibTeX.tab"));

            File.WriteAllText(filename, sb.ToString());

            StatusManager.Instance.UpdateStatus("TabExport", String.Format("Exported your BibTeX tab entries to {0}", filename));
        }
        internal static bool InferBibTeX(PDFDocument pdf_document, bool manual_override)
        {
            if (MustBackoff() && !manual_override)
            {
                return(false);
            }
            if (!pdf_document.DocumentExists)
            {
                return(false);
            }
            if (!String.IsNullOrEmpty(pdf_document.BibTex) && !manual_override)
            {
                return(false);
            }
            if (pdf_document.AutoSuggested_BibTeXSearch && !manual_override)
            {
                return(false);
            }
            if (!ConfigurationManager.Instance.ConfigurationRecord.Metadata_AutomaticallyAssociateBibTeX && !manual_override)
            {
                return(false);
            }

            // Flag on this document that we have tried to do the bibtex
            pdf_document.AutoSuggested_BibTeXSearch = true;
            pdf_document.Bindable.NotifyPropertyChanged(() => pdf_document.AutoSuggested_BibTeXSearch);

            string title = pdf_document.TitleCombined;

            title = title.Trim();
            if (String.IsNullOrEmpty(title))
            {
                return(false);
            }
            if (title.Length < 10)
            {
                return(false);
            }

            // If there is only a single word in the title, it is not useful to us...
            if (-1 == title.IndexOf(' '))
            {
                return(false);
            }

            // Unwanted automatic titles
            if (Constants.TITLE_UNKNOWN == title || pdf_document.DownloadLocation == title)
            {
                return(false);
            }

            // Get the search results!
            string json = DoSearch(title);

            if (null != json)
            {
                object o  = JsonConvert.DeserializeObject(json);
                JArray ja = (JArray)o;

                // Get the bibtexes that suit this document
                List <string> bibtex_choices = new List <string>();
                foreach (var jo in ja)
                {
                    var bibtex = jo["_source"]["bibtex"].ToString();
                    if (String.IsNullOrEmpty(bibtex))
                    {
                        continue;
                    }

                    BibTexItem bibtex_item = BibTexParser.ParseOne(bibtex, true);

                    // Does the bibtex match sufficiently? Empty bibtex will be handled accordingly: no fit/match
                    PDFSearchResultSet search_result_set;
                    if (!BibTeXGoodnessOfFitEstimator.DoesBibTeXMatchDocument(bibtex_item, pdf_document, out search_result_set))
                    {
                        continue;
                    }

                    // Does the title match sufficiently to the bibtex
                    {
                        string title_string         = BibTexTools.GetTitle(bibtex_item);
                        string title_string_tolower = title_string.Trim().ToLower();
                        string title_tolower        = title.Trim().ToLower();
                        double similarity           = StringTools.LewensteinSimilarity(title_tolower, title_string_tolower);
                        if (0.75 > similarity)
                        {
                            continue;
                        }
                    }

                    if (!bibtex.Contains(BibTeXActionComments.AUTO_BIBTEXSEARCH))
                    {
                        bibtex =
                            BibTeXActionComments.AUTO_BIBTEXSEARCH
                            + "\r\n"
                            + bibtex;
                    }

                    // If we get this far, we are happy with the bibtex
                    bibtex_choices.Add(bibtex);
                }

                // Pick the longest matching bibtex
                if (0 < bibtex_choices.Count)
                {
                    bibtex_choices.Sort(delegate(string a, string b)
                    {
                        if (a.Length > b.Length)
                        {
                            return(-1);
                        }
                        if (a.Length < b.Length)
                        {
                            return(+1);
                        }
                        return(0);
                    }
                                        );

                    pdf_document.BibTex = bibtex_choices[0];
                    pdf_document.Bindable.NotifyPropertyChanged(() => pdf_document.BibTex);

                    FeatureTrackingManager.Instance.UseFeature(Features.BibTeX_BibTeXSearchMatch);

                    return(true);
                }
            }

            return(false);
        }