-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathelastic_top
More file actions
196 lines (172 loc) · 14.9 KB
/
elastic_top
File metadata and controls
196 lines (172 loc) · 14.9 KB
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
Sys.sleep(21000)
library(stringr)
library(topicmodels)
library(tm)
library(dplyr)
library(elastic)
library(RCurl)
scanner <- function(x) strsplit(x," ")
stopwords = unique(c("div", "href", "rel", "com", "relnofollow", "про", "что","dneprcity.net","novostimira.com","depo.ua","bbc.com",
"для", "relnofollow", "alt", "zero","img", "alignleft", "hspace", "vspace","studic.info","description","delo.ua",
"alignleft", "hspace", "vspace", "pbrp","altновини", "hrefhttpgsfmopinionhtml", "mode","strong", "pstrong", "targetblank",
"styletext-align", "justifi","altнапк", "classattachment-decosingl", "classreadmor","http:img.ura","pigua.info",
"ethereum", "hrefhttpresonanceua", "hrefhttpsinforesistorg","replyua.net","newsoboz.org","mc.async","manabalss.lv",
"hrefhttpblogiuaus", "hrefhttpvycherpnockua", "hrefhttpwwwkmugovuacontrolukpublisharticleartidampcatid","mid.ru",
"noneimg", "solid", "start", "stylefont-s", "stylefloat", "classfield-item","cackle.me","container","dtp.kiev.ua",
"classfield", "classfield-itemsdiv", "field-label-hiddendiv", "hrefhttpwwwaddthiscombookmarkphpv","replyua.netпро",
"srcbmimgcomuaberlinstoragefinancexebfcbeadfdeccjpg","cackle_widget.push","document.createelement","polytics","loading",
"eff", "i","classfield-item", "classfield", "classfield-itemsdiv", "field-label-hiddendiv", "datatyp","i.lb.ua",
"propertyrdfslabel", "datatyp", "propertyrdfslabel", "skospreflabel", "typeofskosconcept","mc.src","erve.ua","www.pravda.com.ua",
"reldcsubjecta", "classfield-tag", "field-type-taxonomy-term-refer","document.createelement","mc.type","lb.ua",
"classimagecach", "classlink", "classrtejustifyspan", "classtranslation-link", "classtranslationru","goo.gl","newsru.co.il",
"clearfixdiv", "data-colorbox-gallerygallery-node--ytzaljghei","document.getelementbyid","javascript","mon.gov.ua",
"propertyrdfslabel", "skospreflabel","этом","это","які","від","datatyp","-tag","function","innerhtml","sevastopolnews.info",
"hrefhttpkorupciyacom", "дуже", "там", "так", "але","span", "width", "classleftimgimg", "stylecolor", "stylefont-famili",
"hspace", "vspace", "clearal","classback-block","tabletrtd", "valigntop","document.location.protocol","zakarpatpost.net",
"hrefhttpwwwaddthiscombookmarkphpv", "even", "как", "titl","document.getelementsbytagname","text","true","sport.ua",
"sea", "black", "hold", "one","stylemargin", "color", "outlin", "pad", "none","nbsp","widget.js","www.unian.net",
"centerspan", "size", "stylefont-s", "font-siz", "divfont","s.nextsibling","s.parentnode.insertbefore","www.ukrinform.ru",
"justifi", "center", "width", "height", "classfeed-descriptionp","window.cackle_widget","xcoal","politics","newsru.co.il",
"pimg", "wp-post-imag", "margin", "sizesmax-width","justifystrong","joinfo.ua","1news","journal","unn.com.ua","newsonline24",
"srchttpimageunncomuaoriginaljpg", "altновости", "centerimg","styletextalign","stylefontsize","justify","fontsize","padding",
"helvetica","laquoР","raquo","httpnovostimiracomnewshtml","hrefhttprkrinuauploadspostsmatigeroyinyajpg","news_180574",
"hrefhttpskeletinfoorg","pem","leaders","hstrong","development","religious","targetblankstrong","politico","news_180572",
"che","glucosio","person","primarily","hrefhttpskeletinfoorg","classmetanav","clearall","newsoboz","politika","news_180571",
"stylefontfamily","arial","fontfamily","outline","sansserif","textalign","border","inherit","left","pspan","naviny.by",
"justifyspan","rgb","styleboxsizing","small","googleadsectionend","womenbox.net","arianespace","polityka","porfyrios",
"classfielditem","classfielditemsdiv","fieldlabelhiddendiv", "also", "article", "Article","cellpadding","finanso.net",
"download", "google", "figure","fig", "groups","Google", "however","high", "human", "levels","alt","feed","image","src","http",
"jpg", "larger", "may", "number","class","новости","gazeta.ua","rossii.html","zn.ua","cellspacing","portal",
"shown", "study", "studies", "this","img","using", "two", "the", "Scholar","pubmedncbi", "PubMedNCBI","p","photocharles",
"view", "View", "the", "biol","div","via", "image", "doi", "one", "classbackblock","dubinsky.pro","posted","news_180560",
"analysis","nbspap","photocharl","dharapak","pimg", "srcbmimgcomuaberlinstoragenewsxabddbdbajpg", "alignleft", "nbspnbspnbsp", "href",
"fieldnamebody","fieldtypetextwithsummary","title","datatype","fieldtypeimage","typeoffoafimage","www.globallookpress.com",
"classcolorbox","fieldnamefieldimage","fieldtypetaxonomytermreference","rdfsseealso","relogimage","evenidfirstp",
"sizesmaxwidth","wppostimage","sizedecosingle","styledisplayblock","classattachmentdecosingle","hrefhttpspolitekanet",
"httpspolitekanetwpcontentuploadsefebimagexjpeg","httpspolitekanetwpcontentuploadsgettyimageskopiyaxjpg","replyua.net.так",
"httpspolitekanetwpcontentuploadsunianxjpg","httpspolitekanetwpcontentuploadsgettyimagesxjpg","joomla","slavdelo.dn.ua",
"classfielditems","odd", "classfielditem","fieldtypetext","stylewidth","classimage","classimageattachteaser","imageattachnode",
"medium","tahomaarialhelveticasansserif","imagethumbnail","classimagecache","pxa", "fieldfieldnewslead","fieldfieldyandexnews",
"srchttpinmediakitemscachedddddbbecbesjpg","srchttpsgoroddpuapicnewsnewsimagesmjpg","srchttpwwwkanzasuauploadpicresizejpg",
"ampraquo","hrefhttpelvisticomnode","hrefhttpwwwgazetamistoteualajntranslyatsiyaforumudetsentralizatsiyaosnovaformuvannyanovoyisystemyupravlinnyatamistsevogorozvytku",
"forklog","hidden","hrefhttpgiuauseridurlhttpsaffnewstutbyfeconomicsfhtml","lineheight","overflow","colorspan", "pxbbrspan","sizeb",
"srcbmimgcomuaacommonimgicstarsemptyvioletgif","altimg","titleСЂР","hrefhttpvideobigmirnetuser","srchttpbmimgcomuavideoimgsxjpg", "table",
"mediumspan","sansarialsansserifspan","langruruspan","classfooterinfosocialitemfollows","classfooterinfosocialitemiconspan",
"hrefhttpwwwpravdacomuarusnews", "classfbcommentscount","що","который","которые","также","таким","новости","несмотря","в","на","и","не",
"что","у","о","по","с","про","за","з","до","і","що","экс","об","этом","из","к","от","та","для","екс","це","его","а","как","politeka","он",
"від","його","новости","это","твій","года","суті","при","під","после","того","через","будет","так","липня","том","уже","більше","як","все",
"но","щодо","які","которые","то","2017","против","также","далее","новостей","він","своей","також","еще","перед","который","є","под","сути",
"твой","знай","михаил","со","году","року","я","видео","проти","сил","із","сейчас","чтобы","dneprcity.net","же","й","может","над","или",
"стало","было","може","тому","буде","те","был","быть","между","фото","112","який","ua","только","чем","является","ли","более","21",
"26.07.17","без","було","вже","где","зі","ще","19","2018","laquo","мы","raquo","вона","кто","ми","своїй","ст","яких","были","ему","их",
"наших","него","особо","очень","себе","щоб","де","ее","зараз","котором","сам","своем","теперь","цього","але","если","которая","себя",
"тем","эти","https","больше","був","бути","два","навіщо","нас","таки","тогда","replyua.net","будут","йому","між","можно","ним","новость",
"п","ч","чи","12","50","mc","должен","им","именно","источник","которых","меньше","стал","эту","буду","має","стоит","требует","этот","11",
"http","была","высокий","день","имеет","її","мог","несколько","них","она","этого","вони","всего","вся","когда","которым","одним","почти",
"разі","стала","була","всі","вы","даже","дал","дать","кого","которое","м","нет","ни","новину","оборони","один","поки","потому","свою",
"стали","таким","этой","яка","якому","яку","script","the","var","ей","новини","одно","понад","проте","серед","такий","чому","вот","дати","есть"))
q = '{
"query": {
"bool": {
"must": [
{
"exists": {
"field": "title_ru"
}
},
{
"exists": {
"field": "target"
}
}
]
}
}
}'
csv_to_json <- function(dat, pretty = F,na = "null",raw = "mongo",digits = 3,force = "unclass")
{
dat_to_json <- jsonlite::toJSON(dat,pretty = pretty,na = "null",raw = raw,digits = digits ,force = force )
dat_to_json=substr(dat_to_json,start = 2,nchar(dat_to_json)-1)
return(dat_to_json)
}
print(paste("Start connection",Sys.time()))
connect(es_host = "13.59.27.188", es_port = 9200)
es <- "13.59.27.188:9200"
print(paste("Start download",Sys.time()))
res <- Search(index = paste0("urls_",gsub("-","",as.character(Sys.Date()-1))), body=q , type = 'news',source = paste("title_ru","fullhtml",sep = ","),scroll = "1m")
out <- res$hits$hits
hits <- 1
while(hits != 0){
res <- scroll(scroll_id = res$`_scroll_id`)
hits <- length(res$hits$hits)
if(hits > 0)
out <- c(out, res$hits$hits)
}
library(gtools)
out_df <- do.call("smartbind",lapply(out,function(x)as.data.frame(x,stringsAsFactors=F)))
print(paste("Downloaded",Sys.time()))
train_lda <- function(tem,k){
#tem$X_source.descr <- tolower(gsub(">[^<^>]+<", "> <", tem$X_source.descr))
#tem$X_source.descr <- gsub("</[^<^>]+>", "", tem$X_source.descr)
#tem$X_source.fullhtml <- enc2utf8(mapply(function(x,y) paste(x,y,collapse=" "),tem$X_source.title_ru,tem$X_source.fullhtml))
paperCorp <- Corpus(VectorSource(tem$X_source.fullhtml),readerControl = list(language = "ru"))
paperCorp <- tm_map(paperCorp, removePunctuation)
paperCorp <- tm_map(paperCorp, removeNumbers)
paperCorp <- tm_map(paperCorp,tolower)
paperCorp <- tm_map(paperCorp, removeWords, stopwords("english"))
paperCorp <- tm_map(paperCorp, removeWords, stopwords("russian"))
paperCorp <- tm_map(paperCorp, removeWords, stopwords)
#paperCorp <- tm_map(paperCorp, removeWords, tolower(unique(dom$Domain)))
#paperCorp <- tm_map(paperCorp, removeWords, tolower(unique(dom$Источник)))
paperCorp <- tm_map(paperCorp, stemDocument,language="russian")
paperCorp <- tm_map(paperCorp, stripWhitespace)
paperCorp <- tm_map(paperCorp, stringi::stri_trans_general,"Ukrainian-Latin/BGN")
dtm <- DocumentTermMatrix(paperCorp,control=list(tokenize=scanner,wordLengths=c(3, 15)))
dtm<-removeSparseTerms(dtm, sparse=0.99)
rowTotals <- apply(dtm , 1, sum)
dtm.new <<- dtm[rowTotals> 0, ]
control <- list(burnin = 150,
iter = 150,
#seed = 0:4,
#nstart = 5,
best = TRUE)
print(paste("Start learning",Sys.time()))
lda <- LDA(dtm.new, k, method = "Gibbs", control = control)
gammaDF <- as.data.frame(lda@gamma)
names(gammaDF) <- c(1:k)
toptopics <- as.data.frame(cbind(document = row.names(gammaDF),
theme = as.numeric(apply(gammaDF,1,function(x) names(gammaDF)[which(x==max(x))][1]))),stringsAsFactors=F)
toptext <- data_frame(text=tem$X_source.title_ru[rowTotals> 0] ,theme=toptopics$theme)
toptext$theme_quality <- apply(gammaDF,1,max)
toptext <- toptext %>% group_by(text) %>% summarise(theme=min(theme,na.rm=T),theme_quality=mean(theme_quality,na.rm=T))
tem <- left_join(tem,toptext,by=c("X_source.title_ru"="text"))
slov <- left_join((tem %>% group_by(theme) %>% summarise(theme_quality=max(theme_quality)[1])),tem[c(5:8)],by=c("theme_quality","theme"))
names(slov)[3] <- "theme2"
tem <- left_join(tem,slov[-2],by=c("theme"))
tem$theme <- tem$theme2
tem <- distinct(tem[-c(9:10)])
tem[!duplicated(tem[,'X_id']),]
}
print(paste("Start training",Sys.time()))
try(httpPUT(paste(es, paste0("urls_",gsub("-","",as.character(Sys.Date()-1))),"news","theme",sep="/"), csv_to_json(data.frame(dt=paste0(substr(as.character(Sys.time()),1,10),"T",substr(as.character(Sys.time()),12,20),"+0300")))))
startdate=paste0(substr(as.character(Sys.time()),1,10),"T",substr(as.character(Sys.time()),12,20),"+0300")
out_df2 <- train_lda(out_df,2000)
print(paste("Trained",Sys.time()))
names(out_df2) <- c("_index","_type","_id","_score","title_ru","fullhtml","theme","theme_quality")
out_df2 <- na.omit(out_df2)
print(paste("Start writing",Sys.time()))
con<-file(paste0("OU",gsub("-","",as.character(Sys.Date()-1)),".json"),open = 'a',encoding="UTF-8")
for(i in 1:nrow(out_df2)){
write(print(paste0('{"update": {"_id": "',out_df2[i,3],'", "_type" : "news", "_index" : "',
out_df2[i,1],'"}}\n{"doc": {"theme": "',str_replace_all(gsub("|","",
str_replace_all(out_df2[i,7], "[[:punct:]]", "")), "[\r\n]" , ""),'", "theme_quality": ',as.numeric(out_df2[i,8]),'}}')),file=con,
append=TRUE)
}
print(paste("Start bulking",Sys.time()))
Sys.sleep(100)
res <- tryCatch(docs_bulk(paste0("OU",gsub("-","",as.character(Sys.Date()-1)),".json")))
httpPUT(paste(es, paste0("urls_",gsub("-","",as.character(Sys.Date()-1))),"news","theme",sep="/"), csv_to_json(data.frame(dt=startdate,
dtpost=paste0(substr(as.character(Sys.time()),1,10),"T",substr(as.character(Sys.time()),12,20),"+0300"))))
print(paste("Bulked!",Sys.time()))
Sys.sleep(100)
res <- tryCatch(docs_bulk(paste0("OU",gsub("-","",as.character(Sys.Date()-1)),".json")))