summaryrefslogtreecommitdiffstats
path: root/kbabel/kbabeldict/modules/dbsearchengine2/database.cpp
blob: ea0e8379ce6eaa4bd66f7ed28af64345d6b2030c (plain)
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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
/*
  
DBSE 3
(c) 2000-2003 Andrea Rizzi
License: GPLv2 
	 
*/
#include <math.h>
#include "database.h"

#include <qregexp.h>
#include <qdict.h>
#include <kapplication.h>
#include <kdebug.h>
#include <kmessagebox.h>

#define i18n (const char*)






DataBase::DataBase(QString dbpath,QString dbname, QString dblang) : Db(0,DB_CXX_NO_EXCEPTIONS)
{
    
    filename=dbpath+"."+dblang+".db";
    database=dbname;
    
}

int DataBase::open(DBTYPE type,unsigned int flags)
{
    int ret;
    ret = Db::open(
#if DB_VERSION_MINOR > 0
              NULL,
#endif
    (const char*)filename.local8Bit(),(const char *)database.local8Bit(),type,flags,0644);
    mytype=type;
    return ret;
}

unsigned int DataBase::getLast()
{
    if(mytype!=DB_RECNO)
	return 0;
    
    Dbc *cur;
    cursor(0,&cur,0);
    DBItemNum index;
    DBItemMainKey key;
    cur->get(&index,&key,DB_LAST);
    return index.getNum();
    
}





QueryResult::QueryResult(QString r)
{
    res=r;
}
QueryResult::QueryResult(QString r,QString o,int s)
{
    res=r;
    richr=r;
    orig=o;  
    richo=o;
    sco=s;
}

QueryResult::QueryResult()
{
    res="";
}




DataBaseInterface::DataBaseInterface(QString dir, DBSESettings *sets)
{
    
    //FIXME Better db names!!
    main = openMyDataBase(dir+"/testm","main","it",DB_BTREE);
    alpha = openMyDataBase(dir+"/testa","alpha","it",DB_BTREE);
    numindex = openMyDataBase(dir+"/testn","numindex","it",DB_RECNO);
    wordsindex = openMyDataBase(dir+"/testw","wordsindex","it",DB_BTREE);
    sentence = openMyDataBase(dir+"/tests","sentence","it",DB_BTREE);
    corr = openMyDataBase(dir+"/testc","corr","it",DB_BTREE);
    transword = openMyDataBase(dir+"/testt","transword","it",DB_RECNO);
    
    // kdDebug(0) << main << endl;
    // kdDebug(0) << alpha << endl;
    settings=sets;
    _stopNow=false;
}

DataBaseInterface::~DataBaseInterface()
{
    
    if(main){
	main->close(0); 
	delete main;
    }    
    if(numindex){
	numindex->close(0); 
	delete numindex; 
    }
    
    if(alpha){
	alpha->close(0); 
	delete alpha; 
    } 
    if(wordsindex){
	wordsindex->close(0); 
	delete wordsindex; 
    } 
    if(sentence){
	sentence->close(0); 
	delete sentence; 
    }
    
}

DataBase *DataBaseInterface::openMyDataBase(const QString& prefix,const QString& name,const QString& l,DBTYPE tt)
{

    DataBase *aDb = new DataBase(prefix,name,l);
    if(aDb==0){
	return 0;
    }
    else
    {
	if(aDb->open(tt)!=0)
	{
	    kdDebug(0) << "Database '"<< name <<"'do not exist, I try to create it.." << endl;
		//ask only the first time.
	   	static bool create=(	KMessageBox::questionYesNo(0,"Database do not exist. Do you want to create it now?",
		i18n("Create Database"), i18n("Create"), i18n("Do Not Create"))==KMessageBox::Yes);
		if(create)
		if(aDb->open(tt,DB_CREATE)!=0)
		{
		kdDebug(0) << "...cannot create!!"<< endl;
		return 0;
	    }
	    else
	    {
		kdDebug(0) << "...done!" << endl;
		return aDb;
	    }
	}
	
    } 
    return aDb;
}

/*
 *   query functions.
 *
 */


DataBaseInterface::MainEntry DataBaseInterface::get(const QString& query,SearchFilter *filter)
{
    static int counter=1;
    counter++;
    DBItemMainKey k(query);
    DBItemMainData d;
    //int r=
    main->get(&k,&d);
    //  kdDebug(0) << "MAINDB->GET returned: " << r << endl;
    if(counter%5==0) kapp->processEvents(100);
    //  kdDebug(0) << "events processed" << endl;
    return qMakePair(k,d);
    
}

/*
 * put functions
 *                                              *
 */


bool DataBaseInterface::addEntry(QString original,QString translated,InputInfo *info)
{
    DBItemMainKey  mk(original);
    DBItemMainData  md;
    QMap<QString, int> correlationDiff;
    bool newentry=false;
    //try to get
    kdDebug(0) << "Inserting the pair:" << endl;
    kdDebug(0) << "ORIGINAL:" << original << endl;
    kdDebug(0) << "TRANSLATED:" << translated << endl;
    
    if(main->get(&mk,&md)==DB_NOTFOUND)
    {
	kdDebug(0) << "new entry" << endl;
	newentry=true;
	//This is a new entry, create index entry
	DBItemNum *nind;
	int newid=numindex->getLast()+1;
	nind=new DBItemNum(newid);
	numindex->put(nind,&mk);
	
	delete nind;
	
	md.clear();
	md.setIndexnumber(newid);
	
	
	//Update secondary index alpha
	DBItemMainKey ka(simple(original));
	DBItemMultiIndex in;
	if(alpha->get(&ka,&in)==DB_NOTFOUND) in.clear()  ;
	//alpha->get(&ka,&in);
	in.addEntry(newid);
	alpha->put(&ka,&in);
	kdDebug(0) << "Updating the word index " << endl;
	//Update words index
	QStringList ws=words(original);
	for(QStringList::iterator it = ws.begin(); it!=ws.end(); ++it)
	{
	    DBItemMainKey word(*it);
	    DBItemMultiIndex win;
	    if(wordsindex->get(&word,&win)==DB_NOTFOUND) win.clear();
	    win.addEntry(newid);
	    wordsindex->put(&word,&win);
	}
	
	kdDebug(0) << "new entry preparation DONE" << endl;
    } 
    else
    {
	
	kdDebug(0) << "It exists!" <<endl;
    }

    
    //Update sentence index
    QStringList so=sentences(original);
    QStringList st=sentences(translated);
    if(so.count()==st.count() && st.count() >1 ) //we already hav a database for single string.
    {
	kdDebug(0) << "inside sentence loop" << endl;
	for(int i=0; i< so.count() ; i++)
	{
	    DBItemMainKey sk(so[i]);
	    DBItemMainData sd;
	    if(sentence->get(&sk,&sd)==DB_NOTFOUND&&!newentry)
		kdDebug(0) << "Warning: new sentence for old entry, do we changed sentence definition? " << endl;
	    
	    kdDebug(0) << "here alive" << endl;
	    
	    //	    if(clean)
	    sd.removeRef(info->ref());
	    kdDebug(0) << "now alive" << endl;
	    sd.addTranslation(st[i],info->ref());
	    kdDebug(0) << "still alive" << endl;
	    
	    sentence->put(&sk,&sd);
	    
	}
	
	
	
    }
    kdDebug(0) << "Fuzzy sentence archive updated" << endl;
    
    
    
    //Add that translation, link to ref for information on that translation
    
    if(!translated.isEmpty())
    {
	//loop on all translations to update correlation
	QStringList tmpTranslations=md.getTranslations();
	for(QStringList::iterator otIt=tmpTranslations.begin(); otIt!=tmpTranslations.end();++otIt)
	{
	    QStringList wt=words(*otIt);
	    for(QStringList::iterator it = wt.begin(); it!=wt.end(); ++it)
	    {
		if(correlationDiff.contains(*it))
		    correlationDiff[*it]--;
		else
		    correlationDiff[*it]=-1;
	    }
	}

	//clean so that we have only one translation per catalog.
	md.removeRef(info->ref());
	md.addTranslation(translated,info->ref());

	tmpTranslations=md.getTranslations();
	for(QStringList::iterator otIt=tmpTranslations.begin(); otIt!=tmpTranslations.end();++otIt)
	{
	    QStringList wt=words(*otIt);
	    for(QStringList::iterator it = wt.begin(); it!=wt.end(); ++it)
	    {
		if(correlationDiff.contains(*it))
		    correlationDiff[*it]++;
		else
		    correlationDiff[*it]=1;
	    }
	}

	//FIXME: use the correlationDIff map somehow

    }

    //finally put!
    return (main->put(&mk,&md)==0);

}


bool DataBaseInterface::removeEntry(QString original)
{
    DBItemMainKey  mk(original);
    DBItemMainData  md;
    
    //FIXME implement remove 
    //try to get
    if(main->get(&mk,&md)==DB_NOTFOUND)
    {			
	/*      //This is a new entry, create index entry
      DBItemNum *nind;
      int newid=numindex->getLast()+1;
      nind=new DBItemNum(newid);
      numindex->put(nind,&mk); 
      
      delete nind;
      
      md.clear();
      md.setIndexnumber(newid); 
      
      
      //Update secondary index alpha
      DBItemMainKey ka(simple(original));
      DBItemMultiIndex in;
      if(alpha->get(&ka,&in)==DB_NOTFOUND) in.clear()  ;
      //alpha->get(&ka,&in);
      in.addEntry(newid);
      alpha->put(&ka,&in);
      
      //Update words index
      QStringList ws=words(original);
      for(QStringList::iterator it = ws.begin(); it!=ws.end(); it++)
	{
	   DBItemMainKey word(*it);
	   DBItemMultiIndex win;
	   if(wordsindex->get(&word,&win)==DB_NOTFOUND) win.clear();
	   win.addEntry(newid);
	   wordsindex->put(&word,&win);    
	}
	
      //Update sentence index
      QStringList so=sentences(original);
      QStringList st=sentences(translated);
      if(so.count()==st.count() && st.count() >1 ) //we already hav a database for single string.
      {
	  for(int i=0; i< so.count() ; i++)
	  {
	      DBItemMainKey sk(so[i]);
	      DBItemMainKey sd(st[i]); //should be a list i.e. main data?
	      sentence->put(&sk,&sd);    
	      
	  } 
      }
      
*/      
    }
    
    
    return false;
    
}



QMap<QString,float> DataBaseInterface::correlation(QString word,SearchFilter *filter,bool notify, float minSign)
{
    QDict<unsigned int> res;
    // res.setAutoDelete(true);
    QMap<QString, float>final;
    DBItemMultiIndex::IndexList il;
    unsigned int tot=0;
    unsigned int background=0;
    unsigned int nocck;
    QString sword=simple(word);
    DBItemMainKey *k = new DBItemMainKey(sword);	 
    DBItemMultiIndex *d = new DBItemMultiIndex();	 
    if(wordsindex->get(k,d)!=DB_NOTFOUND)
    {
	
	il=d->getList();
	kdDebug(0) << il.count()<<endl;
	tot=0;
	for(QValueList<unsigned int>::iterator it=il.begin();it!=il.end();++it)
	{
	    numindex->get(*it,k);
	    
	    
	    // QValueList<QueryResult> trad=exactMatch(k->getString(),filter);	   
	    
	    MainEntry e=get(k->getString(),filter);
	    QStringList trad=e.second.getTranslations();      
	    
	    nocck=words(k->getString()).contains(sword);
	    for( QStringList::iterator it2=trad.begin();it2!=trad.end();++it2)
	    {
		
		QStringList w=words(*it2);
		unsigned int numWords = w.count()*10+1;
		unsigned int wei=100000/sqrt(numWords);  //weight (is the best one?)
		
		background+=(numWords-nocck)*wei; 	
		QDict<uint> count;
		//count.setAutoDelete(true);
		//FIXME:SET AUTODELETE FOR ALL DICTS
		for(QStringList::iterator it1=w.begin();it1!=w.end();it1++)
		{
		    uint *ip;   
		    if(!(ip=count[*it1])) count.insert(*it1,new uint(1));
		    else
			(*ip)++;  
		}
		
		for(QStringList::iterator it1=w.begin();it1!=w.end();it1++)
		{
		    uint *ip;
		    if(*(count[*it1])==nocck) //add only if same number of entry (it cuts articles)
			if(!(ip=res[*it1])) res.insert(*it1,new uint(wei));
		    else
			(*ip)+=wei;  
		}
		
	    }
	}
	
	unsigned int sqrBG=sqrt((1.0*background+1)/10000);
	
	for(QDictIterator<uint> it(res) ; it.current(); ++it)
	{
	    float sign=1.0*(*(it.current()))/(10000.0*sqrBG);
	    if(sign >minSign){
		final[it.currentKey()]=sign;
		kdDebug(0) << it.currentKey() <<" Score:" << 1.0*(*(it.current()))/10000 << "/" <<sqrBG << " = " <<sign << endl;
	    }
	}
	
	kdDebug(0) << "final count " <<final.count()<< endl;  
    }
    
    return final;
}

QStringList DataBaseInterface::words(QString s)
{
    QString str=simple(s);
    QStringList list;

    int pos;

    do {
	pos=str.find(QRegExp("\\s"));
	//   if(!simple(str.left(pos)).isEmpty())
	//     list.append(simple(str.left(pos)));
	if(!str.left(pos).isEmpty())
	    list.append(str.left(pos));
	str=str.remove(0,pos+1);
    } while(!str.isEmpty() && pos != -1);
    
    return list;
}

QString DataBaseInterface::simple(QString str,bool ck)
{
    QString res;
    if(ck)
	res=str;  //case keep
    else
	res=str.lower();   //lowercase
    //FIXME: uncoment the foll. line (check speed)
    res=res.replace(QRegExp("(<(.*)>)(.*)(</\\2>)"),"\\3"); //remove enclosing tags


	//Try to get rid of regexps.
    //    res=res.replace(QRegExp("(('|-|_|\\s|[^\\w%])+)")," "); //strip non-word char
    //    res=res.replace(QRegExp("(('|-|_)+)")," "); //strip non-word char
    //    res=res.replace(QRegExp("[^\\w\\s%]"),""); //strip non-word char

    QString r;
    QChar c;
    bool wasSpace=true;
    uint len=res.length();
    for(uint i=0; i<len;i++)
    {
	c=res[i];
	if(c.isLetterOrNumber())
	{
	    r+=c;
	    wasSpace=false;
	}
	    else
	{
	    if(!wasSpace && c.isSpace())
	    {
		r+=' ';
		wasSpace=true;
	    }
	    else
	    {
		    if(!wasSpace && (c=='-' || c=='\'' || c=='_'))
		    {
			r+=' ';
			wasSpace=true;
		    }
		    else
		    {
			if(c=='%'){
			    r+=c;
			    wasSpace=false;
			}
		    }
		}
	}
	    //	wasSpace=c.isSpace();
	}
    if(r[len-1].isSpace())
	r.truncate(len-1);
    res=r;
    //kdDebug(0) << "Simple: "<<res<< endl;
    //res=res.simplifyWhiteSpace(); //remove double spaces
    //res=res.stripWhiteSpace(); //"  as " -> "as"
    
    // kdDebug(0) << res << endl;
    return res;
}

QStringList DataBaseInterface::sentences(QString s)
{
    QString str=s;
    QStringList list;
    
    //  kdDebug(0) << s << endl;
    
    int pos;
    
    
    do {
	QRegExp re("((\\.|;|\\?|\\!|:)( |$|\\\\n\\n))");
	pos=re.search(str); 
	if(!str.left(pos).isEmpty())
	    list.append(str.left(pos).stripWhiteSpace());
	
	kdDebug(0) << str.left(pos) << endl;
	
	str=str.remove(0,pos+re.cap(1).length());
    } while(!str.isEmpty() && pos != -1);
    
    
    return list;
}

QStringList DataBaseInterface::sentencesSeparator(QString s)
{
    QString str=s;
    QStringList list;
    
    //  kdDebug(0) << s << endl;
    
    int pos;
    
    do {
	QRegExp re;
	re.setPattern("([.:?!;]( |$|\\\\n\\n))");
	pos = re.search(str);
	QString separator=re.cap(1);
	if(pos!=-1){
	    list.append(separator);
	}
	
	str=str.remove(0,pos+1);
    } while(!str.isEmpty() && pos != -1);
    
    return list;
}

bool DataBaseInterface::isUpper(QChar s)
{
    return s==s.upper();
}

bool DataBaseInterface::isLower(QChar s)
{
    return s==s.lower();
}



QString DataBaseInterface::format(QString _s,QString t)
{
    //FIXME use settings
    //FIXME use regexp

    QString s=_s;
	QString noTagT=t.replace(QRegExp("(<(.*)>)(.*)(</\\2>)"),"\\3");
    QChar first=noTagT[noTagT.find(QRegExp("\\w"))];
    bool firstCapital=isUpper(first);

    /*
bool dotsAtEnd=(t.find("...")+3==t.length());
bool gtgtAtEnd=(t.find(">>")+2==t.length());
bool ltltAtEnd=(t.find("<<")==t.length()-2);

bool columnAtEnd=(t.find(":")+1==t.length());
*/
    
    bool allupper=(t.upper()==t);
    
    
    if(firstCapital)
	s[0]=s[0].upper();
    else
	s[0]=s[0].lower();
    
    //if(dotsAtEnd)
    // s+="...";
    
    /*if(gtgtAtEnd)
 s+=">>";
 
if(ltltAtEnd)
 s+="<<";
 
if(columnAtEnd)
 s+=":";
*/
    
    if(allupper)
	s=s.upper();
    
    int pos=t.find(QRegExp("&"));
    if(pos>=0) {
	QChar accel=t[t.find(QRegExp("&"))+1];
	if(accel!='&')
	{
	    
	    pos=s.find(accel,false);
	    if(pos<0)
		pos=0;
	    s.insert(pos,"&");
	}
    }
    s=formatRegExp(s,t,".*(\\.\\.\\.|:|>>|<<|\\.|\\?)$",
		   "^(.*)$",
		   "\\1@CAP1@");
    s=formatRegExp(s,t,"(<(.*)>).*(\\.\\.\\.|:|>>|<<|\\.|\\?)*(</\\2>)$",
		   "^(.*)$",
		   "@CAP1@\\1@CAP3@@CAP4@");
    
    return s;
    
}


QString DataBaseInterface::formatRegExp(QString _s, QString t, QString tre,QString stringSearch,QString stringReplace)
{   
    QString s=_s;
    QRegExp templateRegExp(tre);
    //QString stringSearch = "(.*)!@CAP1@$";  // use @CAP1.. fot caps in templates
    //QString stringReplace = "\\1@CAP1@"; // use \1, \2 for caps in str and @CAP1 fot caps in template
    
    
    if(templateRegExp.exactMatch(t))
    {
	QStringList caps=templateRegExp.capturedTexts();
	int i=0;
	for(QStringList::iterator capit=caps.begin();capit!=caps.end();++capit)
	{
	    QString phRegExp="(?!\\\\)@CAP"+QString::number(i)+"@";
	    //kdDebug(0) << "phRegExp: " << phRegExp << endl;
	    //kdDebug(0) << "cap[" << i << "]: "<< *capit<< endl;
	    
	    stringReplace = stringReplace.replace(QRegExp(phRegExp),*capit);
	    stringSearch = stringSearch.replace(QRegExp(phRegExp),*capit);
	    i++;
	    
	}
	// kdDebug(0) << "stringSearch " << stringSearch << endl;      
	//  kdDebug(0) << "stringReplace " << stringReplace << endl;
	QRegExp stringSearchRegExp = QRegExp(stringSearch);
	//  kdDebug(0) << "before: "<<s<<endl;
	s = s.replace(stringSearchRegExp,stringReplace);
	//  kdDebug(0) << "after: "<<s<<endl;
	
    }
    
    return s;
}

DBItemMultiIndex::IndexList DataBaseInterface::getAlpha( const QString & query )
{
    DBItemMainKey *k = new DBItemMainKey(simple(query));
    DBItemMultiIndex *d = new DBItemMultiIndex();
    alpha->get(k,d);    
    
    return d->getList();
}

DataBaseInterface::MainEntry DataBaseInterface::getFromIndex( uint i )
{
    DBItemMainKey k;
    numindex->get(i,&k);
    return get(k.getString(),0); //FIXME: this is a BUG right now but the filter should be removed
}

DataBaseInterface::MainEntry DataBaseInterface::getSentence( const QString & query )
{ 
    
    static int counter=1;
    counter++;
    DBItemMainKey k(query);
    DBItemMainData d;
    sentence->get(&k,&d);
    if(counter%5==0) kapp->processEvents(100);
    return qMakePair(k,d);
    
}

DBItemMultiIndex::IndexList DataBaseInterface::getWordIndex( const QString & query )
{
    DBItemMainKey k = DBItemMainKey(query);	 
    DBItemMultiIndex d =  DBItemMultiIndex();	 
    if(wordsindex->get(&k,&d)!=DB_NOTFOUND){
	return d.getList();
    }
    else
    {	
	QValueList<unsigned int> tmpList;
	return tmpList; 
    }
    
}



//#include "database.moc.cpp"