reccomender similarity genere

This commit is contained in:
Giampiero Galeazzi
2019-02-28 19:19:28 +01:00
parent a4752a42da
commit 0e48971e1e
9 changed files with 51 additions and 126 deletions
+6
View File
@@ -62,6 +62,9 @@ low(new FileAsync(__dirname + '/db.json')) // production
// GET /videotrack
app.get('/videotrack', (req, res) => {
res.set({
'Access-Control-Allow-Origin': '*'
});
const videos = db.get('videos');
req.query.id ? res.send(videos.getById(req.query.id).value()) : res.send(videos.value())
});
@@ -94,5 +97,8 @@ low(new FileAsync(__dirname + '/db.json')) // production
})
.then(() => {
app.use(express.static(__dirname + '/build')); // serve static build site
app.get('*', (req,res) =>{
res.sendFile(__dirname+'/build/index.html');
});
app.listen(8000, () => console.log('listen on 8000')); // bind to port 8000 as required from specs
});
+4
View File
@@ -6,6 +6,7 @@ import VideoPlayer from './VideoPlayer';
import VideoInfo from './VideoInfo';
import VideoList from './VideoList';
import Suggestion from './Suggestion';
import AboutUs from './AboutUs';
import { ReactHeight } from 'react-height';
import './css/App.css';
@@ -91,6 +92,9 @@ class App extends React.Component {
<Route render={() => <div>URL not found</div>} />
</Switch>
</Row>
<Row id="AboutUs">
<Route exact path="/" component={AboutUs} />
</Row>
</React.Fragment>
);
}
-53
View File
@@ -1,53 +0,0 @@
import React, { Component } from 'react';
import { Row, Col } from 'react-bootstrap';
import { Switch, Route } from 'react-router';
import Random from './reccomenders/Random';
import Related from './reccomenders/Related';
import Search from './reccomenders/Search';
import fvitali from './reccomenders/fvitali';
import popGlobaleAssoluta from './reccomenders/popGlobaleAssoluta';
import Recent from './reccomenders/Recent';
// and so on..
class Suggestion extends Component {
// static getDerivedStateFromProps(nextProps, prevState) {
// }
// componentDidMount() {
// }
// shouldComponentUpdate(nextProps, nextState) {
// }
// componentDidUpdate(prevProps, prevState) {
// }
// componentWillUnmount() {
// }
render() {
return (
<React.Fragment>
<Switch>
<Route path='/video/:id/vitali' component={fvitali} />
<Route path='/search/:query' component={Search} />
<Route path='/video/:id/random' component={Random} />
<Route path='/video/:id/popGlobalAssoluta' component={popGlobaleAssoluta} />
<Route path='/video/:id/recent' component={Recent} />
{/* lasciare questo per ultimo */}
<Route component={Related} />
</Switch>
</React.Fragment>
);
}
}
export default Suggestion;
+2 -2
View File
@@ -42,7 +42,7 @@ class TopBar extends Component {
<Link to={{ pathname: `/video/${localStorage['lastId']}/related` }} className="text-light nav-link">Related</Link>
{<NavDropdown title="Similarity" id="basic-nav-dropdown" >
<Link to={{ pathname: `/video/${localStorage['lastId']}/...` }} className="text-dark nav-link">
<Link to={{ pathname: `/video/${localStorage['lastId']}/similarityArtist` }} className="text-dark nav-link">
Artist
</Link>
@@ -54,7 +54,7 @@ class TopBar extends Component {
</NavDropdown>}
{<NavDropdown title="Popolarità locale" id="basic-nav-dropdown" >
<Link to={{ pathname: `/video/${localStorage['lastId']}/...` }} className="text-dark nav-link">
<Link to={{ pathname: `/video/${localStorage['lastId']}/popLocaleAss` }} className="text-dark nav-link">
Assoluta
</Link>
+4 -1
View File
@@ -86,9 +86,11 @@ class VideoPlayer extends React.Component {
.then(
videoIdWatched => {
// post request to local db
let reason = new URLSearchParams(this.props.location.search).get("ref");
axios
.post('http://site1854.tw.cs.unibo.it/videotrack', {
id: videoIdWatched.toString()
id: videoIdWatched.toString(),
reason: reason || undefined
})
.then(
response => console.info(response.data),
@@ -107,6 +109,7 @@ class VideoPlayer extends React.Component {
tmp[j].timesWatched++;
tmp[j].lastWatched= new Date();
}
tmp.sort((a, b) => new Date(b.lastWatched).getTime() - new Date(a.lastWatched).getTime());
localStorage.setItem('lastWatched', JSON.stringify(tmp));
+32 -23
View File
@@ -41,6 +41,8 @@ class Wikipedia extends Component {
return ( <Link to={{pathname:`/video/${value}`}}>{`${value}`}</Link>)
case "P2581":
return (<a target="_blank" rel="noopener noreferrer" href={`https://babelnet.org/synset?word=bn:${value}`}>{`${value}`}</a>)
case "P1827":
return (<a target="_blank" rel="noopener noreferrer" href={`https://musicbrainz.org/iswc/${value}`}>{`${value}`}</a>)
default:
return(`${value}`)
}
@@ -87,18 +89,18 @@ class Wikipedia extends Component {
}
findWikiPage = () => {
let wikiquery = `${'undefined' === typeof this.props.title ? this.props.title2.trim() : this.props.title.trim()} (${'undefined' === typeof this.props.artist ? this.props.artist2.trim() : this.props.artist.trim()} song)`;
console.info(wikiquery)
let wikiquery = `${'undefined' === typeof this.props.title ? ('undefined' === typeof this.props.title2 ? this.props.artist2 : this.props.title2) : this.props.title.trim()} ${'undefined' === typeof this.props.title && 'undefined' === typeof this.props.title2 ? "" : `(${'undefined' === typeof this.props.artist ? this.props.artist2.trim() : this.props.artist.trim()} song)`}`;
return wikijs()
.find(wikiquery)
.then(res => {
console.info(res, 'a');
return Promise.all([res.fullInfo(), res.summary()]);
// return Promise.all([res.fullInfo(), res.links(), res.backlinks()]);
return Promise.all([res.fullInfo()]);
}) // find by props.title (props.artist song)
.then(wikipediaRes => this.setState({
wikipedia: {
"desc": wikipediaRes[1],
"info": wikipediaRes[0].general
// ,"links": wikipediaRes[1],
// "backlinks": wikipediaRes[2]
},
wikipediakeys: Object.keys(wikipediaRes[0].general),
isWikiLoaded: true
@@ -107,7 +109,7 @@ class Wikipedia extends Component {
componentDidMount() {
const musicbrainzBaseUrl = "https://musicbrainz.org/ws/2"; // more readable
// let timerId1;
let timerId1;
axios.get(wdk.getReverseClaims('P1651', this.props.videoId)) // P1651 is youtube_video_id property
.then(wikidataP1651Res => {
if (wikidataP1651Res.data.results.bindings.length) { // got a match
@@ -154,7 +156,7 @@ class Wikipedia extends Component {
else { //oof
axios.get(`${musicbrainzBaseUrl}/work`, {
params: {
'query': 'undefined' === typeof this.props.title ? 'undefined' === typeof this.props.title2 ? this.props.artist2 : this.props.title2 : this.props.title,
'query': 'undefined' === typeof this.props.title ? ('undefined' === typeof this.props.title2 ? this.props.artist2 : this.props.title2) : this.props.title,
'limit': 1,
'offset': 0,
'fmt': 'json'
@@ -180,7 +182,7 @@ class Wikipedia extends Component {
else if (musicbrainzWorkRes.data.relations.find(currentRel => currentRel.type === "wikidata")) { // found wikidata on music brainz
let wikidataUrl = musicbrainzWorkRes.data.relations.find(currentRel => currentRel.type === "wikidata");
let wikidataEntityRegEx = new RegExp("[^/]+$"); // match last part of url https://regex101.com/r/0wCQHY/1
this.getWikidataPage(wikidataEntityRegEx.exec(wikidataUrl.url.resource)) //.then(() => this.setState({ isWikiLoaded: true }));
this.getWikidataPage(wikidataEntityRegEx.exec(wikidataUrl.url.resource))
}
else { // oof
this.findWikiPage()
@@ -189,16 +191,26 @@ class Wikipedia extends Component {
)
})
}
}).finally(() => {
// let tmp = JSON.parse(localStorage['currentVideoInfo']);
// tmp.id = this.props.videoId;
// tmp.artist = this.state.wikipedia.info.artist;
// tmp.genre = this.state.wikidataQ[this.state.wikidata.claims["P136"][0].mainsnak.datavalue.value.id].labels.en.value;
// console.info(tmp)
// // localStorage.setItem('currentVideoInfo',JSON.stringify(tmp));
this.setState({ isLoaded: true })
});
return new Promise ((resolve,reject) => {
timerId1 = window.setInterval(()=>{
if((this.state.wikipedia !== 'undefined') && (this.state.wikidataQ !== 'undefined') && (this.state.wikidata !== 'undefined'))
resolve({
artist: this.state.wikipedia.info.artist.toString(),
genre: this.state.wikidataQ[this.state.wikidata.claims["P136"][0].mainsnak.datavalue.value.id].labels.en.value.toString()
})
}, 700)
})
}).then((res) => {
let tmp = JSON.parse(localStorage['currentVideoInfo']);
window.clearInterval(timerId1);
tmp = {
id: this.props.videoId.toString(),
artist: res.artist,
genre: res.genre
}
localStorage.setItem('currentVideoInfo',JSON.stringify(tmp));
})
.finally(()=>this.setState({ isLoaded: true }));
}
@@ -225,8 +237,6 @@ class Wikipedia extends Component {
</Col>;
} else {
return (
// <>
// {isWikiLoaded && wikipedia.desc}
<Table size="sm">
<tbody>
{isWikiLoaded &&
@@ -244,9 +254,9 @@ class Wikipedia extends Component {
${key[1].labels.en ? key[1].labels.en.value : ""} `}
</td>
<td>{
typeof wikidata.claims[key[0]][0].mainsnak.datavalue.value === "string" ?
typeof wikidata.claims[key[0]][0].mainsnak.datavalue.value === "string" ? // wikidata external
this.getExternalLink(key[0],wikidata.claims[key[0]][0].mainsnak.datavalue.value) :
typeof wikidata.claims[key[0]][0].mainsnak.datavalue.value.id === "string" ?
typeof wikidata.claims[key[0]][0].mainsnak.datavalue.value.id === "string" ? // wikidata Q
<><a target="_blank" rel="noopener noreferrer" href={`https://www.wikidata.org/wiki/${wikidata.claims[key[0]][0].mainsnak.datavalue.value.id}`}>
{`${this.state.wikidataQ[wikidata.claims[key[0]][0].mainsnak.datavalue.value.id].labels.en ?
this.state.wikidataQ[wikidata.claims[key[0]][0].mainsnak.datavalue.value.id].labels.en.value :
@@ -277,7 +287,6 @@ class Wikipedia extends Component {
}
</tbody>
</Table>
// </>
);
}
}
-45
View File
@@ -1,6 +1,3 @@
//http://site1825.tw.cs.unibo.it/TW/globpop fvitali
//http://site1825.tw.cs.unibo.it/video.json originale videolist
import React from 'react';
import { Col, ListGroup, Card, CardDeck } from 'react-bootstrap'; // eslint-disable-line no-unused-vars
import axios from 'axios'; // eslint-disable-line no-unused-vars
@@ -21,39 +18,7 @@ class Recent extends React.Component {
}
componentDidMount() {
// axios.get('http://site1825.tw.cs.unibo.it/TW/globpop', {
// 'params':{
// 'id':this.props.id
// }
// }).then(
// response => {
// //this.shuffleArray(response.data);
// console.info ('a',response.data);
this.getThumbnailsNames(JSON.parse(localStorage.getItem('lastWatched')));
let lastWatchedList = JSON.parse(localStorage.getItem('lastWatched')).map(x =>x.lastWatched)
let now = moment(new Date()); // riferimento unico temporale
let timePast = lastWatchedList.map(item => now.diff(item)) // differenza in secondi tra adesso e lastWatched
console.info(lastWatchedList, timePast.sort((a, b) => a - b))
// console.info(response.data.recommended);
// // this.setState({
// // isLoaded: true,
// // items:response.data.recommended,
// // });
// },
// // Note: it's important to handle errors here
// // instead of a catch() block so that we don't swallow
// // exceptions from actual bugs in components.
// error => {
// console.error(error);
// this.setState({
// isLoaded: true,
// error
// });
// }
// );
}
// METODI
@@ -90,16 +55,6 @@ class Recent extends React.Component {
}
/*shuffleArray(videoarray) {
for (let i = videoarray.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[videoarray[i], videoarray[j]] = [videoarray[j], videoarray[i]]; // eslint-disable-line no-param-reassign
}
// Durstenfeld shuffle.
// https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_modern_algorithm
}*/
render() {
const recentVideoList = JSON.parse(localStorage.getItem('lastWatched'))
const { error, isLoaded, items } = this.state;
+1 -1
View File
@@ -106,7 +106,7 @@ class Search extends React.Component {
return <React.Fragment>{this.state.error.message} -- {this.state.error.response.data.error.errors[0].reason} </React.Fragment>;
} else if (!this.state.isLoaded) {
return <Col className="text-center">
<div class="lds-ellipsis"><div></div><div></div><div></div><div></div></div>
<div className="lds-ellipsis"><div></div><div></div><div></div><div></div></div>
</Col>;
} else {
return (
+2 -1
View File
@@ -117,7 +117,8 @@ class fvitali extends React.Component {
key={item.videoID}
as="li" className="media mx-5 my-1 suggItem"
to={{
pathname: '/video/' + item.videoID,
pathname: `/video/${item.videoID}`,
search: '?ref=fvitali587'
}}>
<img
width={240}