[
  {
    "path": "LICENSE",
    "content": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright 2018 Mohammad Asif\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "README.md",
    "content": "# Movie-Recommender-System\nA Web Base user-item Movie Recommendation Engine using Collaborative Filtering By matrix factorizations algorithm and\nThe recommendation based on the underlying idea that is if two persons both liked certian common movies,then the movies that one person has liked that the other person has not yet watched can be recommended to him.   \n### Screenshot\n\n###### Home page\n![home](https://user-images.githubusercontent.com/20842692/45380125-941d7500-b61f-11e8-852d-c09e9586b35b.png)\n\n###### Recommendation page\n![recom](https://user-images.githubusercontent.com/20842692/45380167-b57e6100-b61f-11e8-8ec0-e07c26daa4a3.jpg)\n\n###### Rating page\n![rate](https://user-images.githubusercontent.com/20842692/45380186-be6f3280-b61f-11e8-8ad6-8b967d1cba1a.png)\n\n### Technologies Used\n\n#### Web Technologies\nHtml , Css , JavaScript , Bootstrap , Django\n\n#### Machine Learning Library In Python3\nNumpy , Pandas , Scipy\n\n#### Database\nSQLite\n\n##### Requirements\n```\npython 3.6\n\npip3\n\nvirtualenv\n```\n##### Setup to run\n\nExtract zip file in your computer\n\nOpen terminal/cmd promt\n\nGoto that Path\n\nExample\n\n```\ncd ~/Destop/Movie-Recommender-System\n```\nCreate a new virtual environment on that directory\n\n```\nvirtualenv .\n```\n\nActivate Your Virtual Environment\n\nfor Linux\n```\nsource bin/activate\n```\nfor Windows\n```\ncd Scripts\nthen\nactivate\n```\nTo install Dependencies\n\n```\npip install -r requirements.txt\n```\n\n### Creating Local Server\n\nGoto src directory, example\n\n```\ncd ../Movie-Recommender-System/src\n```\nTo run\n```\npython manage.py runserver\n```\nNow open your browser and go to this address\n```\nhttp://127.0.0.1:8000\n```\nThank you for visiting my repository.\n"
  },
  {
    "path": "requirements.txt",
    "content": "Django==2.0.12\npandas==0.23.3\nnumpy==1.14.5\nscipy==1.1.0\n"
  },
  {
    "path": "src/main/__init__.py",
    "content": ""
  },
  {
    "path": "src/main/settings.py",
    "content": "\"\"\"\nDjango settings for main project.\n\nGenerated by 'django-admin startproject' using Django 2.0.7.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/2.0/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/2.0/ref/settings/\n\"\"\"\n\nimport os\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = '5u$a%1-m#+jh4k^pb%*ut#24zhwxdv@)ks3=tg7sz9&7)&dr^j'\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = True\n\nALLOWED_HOSTS = []\n\n\n# Application definition\n\nINSTALLED_APPS = [\n    'web.apps.WebConfig',\n    'django.contrib.admin',\n    'django.contrib.auth',\n    'django.contrib.contenttypes',\n    'django.contrib.sessions',\n    'django.contrib.messages',\n    'django.contrib.staticfiles',\n    \n]\n\nMIDDLEWARE = [\n    'django.middleware.security.SecurityMiddleware',\n    'django.contrib.sessions.middleware.SessionMiddleware',\n    'django.middleware.common.CommonMiddleware',\n    'django.middleware.csrf.CsrfViewMiddleware',\n    'django.contrib.auth.middleware.AuthenticationMiddleware',\n    'django.contrib.messages.middleware.MessageMiddleware',\n    'django.middleware.clickjacking.XFrameOptionsMiddleware',\n]\n\nROOT_URLCONF = 'main.urls'\n\nTEMPLATES = [\n    {\n        'BACKEND': 'django.template.backends.django.DjangoTemplates',\n        'DIRS': [],\n        'APP_DIRS': True,\n        'OPTIONS': {\n            'context_processors': [\n                'django.template.context_processors.debug',\n                'django.template.context_processors.request',\n                'django.contrib.auth.context_processors.auth',\n                'django.contrib.messages.context_processors.messages',\n            ],\n        },\n    },\n]\n\nWSGI_APPLICATION = 'main.wsgi.application'\n\n\n# Database\n# https://docs.djangoproject.com/en/2.0/ref/settings/#databases\n\nDATABASES = {\n    'default': {\n        'ENGINE': 'django.db.backends.sqlite3',\n        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),\n    }\n}\n\n\n# Password validation\n# https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators\n\nAUTH_PASSWORD_VALIDATORS = [\n    {\n        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',\n    },\n    {\n        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',\n    },\n    {\n        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',\n    },\n    {\n        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',\n    },\n]\n\n\n# Internationalization\n# https://docs.djangoproject.com/en/2.0/topics/i18n/\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'UTC'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/2.0/howto/static-files/\n\nSTATIC_URL = '/static/'\n\nSTATICFILES_DIRS = [\n    os.path.join(BASE_DIR, \"static\"),\n    '/var/www/static/',\n]\n\nMEDIA_ROOT = os.path.join(BASE_DIR, 'media')\nMEDIA_URL = '/media/'\n\n"
  },
  {
    "path": "src/main/urls.py",
    "content": "\"\"\"main URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n    https://docs.djangoproject.com/en/2.0/topics/http/urls/\nExamples:\nFunction views\n    1. Add an import:  from my_app import views\n    2. Add a URL to urlpatterns:  path('', views.home, name='home')\nClass-based views\n    1. Add an import:  from other_app.views import Home\n    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')\nIncluding another URLconf\n    1. Import the include() function: from django.urls import include, path\n    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path,include\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\nurlpatterns = [\n\tpath('',include('web.urls')),\n    path('admin/', admin.site.urls),\n\n]\nif settings.DEBUG:\n\turlpatterns +=static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\n\turlpatterns +=static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n\n"
  },
  {
    "path": "src/main/wsgi.py",
    "content": "\"\"\"\nWSGI config for main project.\n\nIt exposes the WSGI callable as a module-level variable named ``application``.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/2.0/howto/deployment/wsgi/\n\"\"\"\n\nimport os\n\nfrom django.core.wsgi import get_wsgi_application\n\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"main.settings\")\n\napplication = get_wsgi_application()\n"
  },
  {
    "path": "src/manage.py",
    "content": "#!/usr/bin/env python\nimport os\nimport sys\n\nif __name__ == \"__main__\":\n    os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"main.settings\")\n    try:\n        from django.core.management import execute_from_command_line\n    except ImportError as exc:\n        raise ImportError(\n            \"Couldn't import Django. Are you sure it's installed and \"\n            \"available on your PYTHONPATH environment variable? Did you \"\n            \"forget to activate a virtual environment?\"\n        ) from exc\n    execute_from_command_line(sys.argv)\n"
  },
  {
    "path": "src/web/__init__.py",
    "content": ""
  },
  {
    "path": "src/web/admin.py",
    "content": "from django.contrib import admin\nfrom .models import Movie,Myrating\n\nadmin.site.register(Movie)\nadmin.site.register(Myrating)\n# Register your models here.\n"
  },
  {
    "path": "src/web/apps.py",
    "content": "from django.apps import AppConfig\n\n\nclass WebConfig(AppConfig):\n    name = 'web'\n"
  },
  {
    "path": "src/web/forms.py",
    "content": "from django.contrib.auth.models import User\nfrom django import forms\n\nclass UserForm(forms.ModelForm):\n    password = forms.CharField(widget=forms.PasswordInput)\n\n    class Meta:\n        model = User\n        fields = ['username', 'email', 'password']\n\n\n\t\t\t\n\n\n\n\n\t\t\n\t\t\n\n\n"
  },
  {
    "path": "src/web/migrations/0001_initial.py",
    "content": "# Generated by Django 2.0.7 on 2018-07-18 18:25\n\nfrom django.conf import settings\nimport django.core.validators\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n    initial = True\n\n    dependencies = [\n        migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n    ]\n\n    operations = [\n        migrations.CreateModel(\n            name='Movie',\n            fields=[\n                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n                ('title', models.CharField(max_length=200)),\n                ('genre', models.CharField(max_length=100)),\n                ('movie_logo', models.FileField(upload_to='')),\n            ],\n        ),\n        migrations.CreateModel(\n            name='Myrating',\n            fields=[\n                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n                ('rating', models.IntegerField(default=1, validators=[django.core.validators.MaxValueValidator(5), django.core.validators.MinValueValidator(0)])),\n                ('movie', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='web.Movie')),\n                ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),\n            ],\n        ),\n    ]\n"
  },
  {
    "path": "src/web/migrations/__init__.py",
    "content": ""
  },
  {
    "path": "src/web/models.py",
    "content": "from django.contrib.auth.models import Permission, User\nfrom django.core.validators import MaxValueValidator, MinValueValidator\nfrom django.db import models\n\nclass Movie(models.Model):\n\ttitle   \t= models.CharField(max_length=200)\n\tgenre  \t\t= models.CharField(max_length=100)\n\tmovie_logo  = models.FileField() \n\n\tdef __str__(self):\n\t\treturn self.title\n\nclass Myrating(models.Model):\n\tuser   \t= models.ForeignKey(User,on_delete=models.CASCADE) \n\tmovie \t= models.ForeignKey(Movie,on_delete=models.CASCADE)\n\trating \t= models.IntegerField(default=1,validators=[MaxValueValidator(5),MinValueValidator(0)])\n\t\t"
  },
  {
    "path": "src/web/recommendation.py",
    "content": "import numpy as np \nimport pandas as pd\nfrom web.models import Myrating\nimport scipy.optimize \n\n\ndef Myrecommend():\n\tdef normalizeRatings(myY, myR):\n    \t# The mean is only counting movies that were rated\n\t\tYmean = np.sum(myY,axis=1)/np.sum(myR,axis=1)\n\t\tYmean = Ymean.reshape((Ymean.shape[0],1))\n\t\treturn myY-Ymean, Ymean\n\t\n\tdef flattenParams(myX, myTheta):\n\t\treturn np.concatenate((myX.flatten(),myTheta.flatten()))\n    \n\tdef reshapeParams(flattened_XandTheta, mynm, mynu, mynf):\n\t\tassert flattened_XandTheta.shape[0] == int(mynm*mynf+mynu*mynf)\n\t\treX = flattened_XandTheta[:int(mynm*mynf)].reshape((mynm,mynf))\n\t\treTheta = flattened_XandTheta[int(mynm*mynf):].reshape((mynu,mynf))\n\t\treturn reX, reTheta\n\n\tdef cofiCostFunc(myparams, myY, myR, mynu, mynm, mynf, mylambda = 0.):\n\t\tmyX, myTheta = reshapeParams(myparams, mynm, mynu, mynf)\n\t\tterm1 = myX.dot(myTheta.T)\n\t\tterm1 = np.multiply(term1,myR)\n\t\tcost = 0.5 * np.sum( np.square(term1-myY) )\n    \t# for regularization\n\t\tcost += (mylambda/2.) * np.sum(np.square(myTheta))\n\t\tcost += (mylambda/2.) * np.sum(np.square(myX))\n\t\treturn cost\n\n\tdef cofiGrad(myparams, myY, myR, mynu, mynm, mynf, mylambda = 0.):\n\t\tmyX, myTheta = reshapeParams(myparams, mynm, mynu, mynf)\n\t\tterm1 = myX.dot(myTheta.T)\n\t\tterm1 = np.multiply(term1,myR)\n\t\tterm1 -= myY\n\t\tXgrad = term1.dot(myTheta)\n\t\tThetagrad = term1.T.dot(myX)\n    \t# Adding Regularization\n\t\tXgrad += mylambda * myX\n\t\tThetagrad += mylambda * myTheta\n\t\treturn flattenParams(Xgrad, Thetagrad)\n\n\tdf=pd.DataFrame(list(Myrating.objects.all().values()))\n\tmynu=df.user_id.unique().shape[0]\n\tmynm=df.movie_id.unique().shape[0]\n\tmynf=10\n\tY=np.zeros((mynm,mynu))\n\tfor row in df.itertuples():\n\t\tY[row[2]-1, row[4]-1] = row[3]\n\tR=np.zeros((mynm,mynu))\n\tfor i in range(Y.shape[0]):\n\t\tfor j in range(Y.shape[1]):\n\t\t\tif Y[i][j]!=0:\n\t\t\t\tR[i][j]=1\n\n\tYnorm, Ymean = normalizeRatings(Y,R)\n\tX = np.random.rand(mynm,mynf)\n\tTheta = np.random.rand(mynu,mynf)\n\tmyflat = flattenParams(X, Theta)\n\tmylambda = 12.2\n\tresult = scipy.optimize.fmin_cg(cofiCostFunc,x0=myflat,fprime=cofiGrad,args=(Y,R,mynu,mynm,mynf,mylambda),maxiter=40,disp=True,full_output=True)\n\tresX, resTheta = reshapeParams(result[0], mynm, mynu, mynf)\n\tprediction_matrix = resX.dot(resTheta.T)\n\treturn prediction_matrix,Ymean\n\t\n\n\n\n\n\n\n\n"
  },
  {
    "path": "src/web/static/web/css/base.css",
    "content": ".navbar{\n\tborder-radius: 0;\n\tmin-height: 80px;\n}\n.container-fluid{\n\tmargin-top: 18px;\n}\n.navbar-nav>li>a{\n\tfont-size: 18px;\n}\n.navbar-brand{\n\tfont-size: 22px;\n\tfont-family: inherit;\n\tfont-style: italic;\n\tfont-weight: 700;\n}\n.navbar-inverse .navbar-brand{\n\tcolor:#00bcd4;\n}\n.navbar-inverse .navbar-nav>li>a{\n\t\tcolor: #00bcd4;\t\n}\nh2{\n\tmargin-left: 20px;\n}\n\n#social-fb:hover {\n     color: #3B5998;\n }\n #social-tw:hover {\n     color: #4099FF;\n }\n\n #social-em:hover {\n     color: #f39c12;\n }\n #social-git:hover{\n \tcolor:black;\n }\n* {\n    margin: 0;\n}\nhtml, body {\n    height: 100%;\n}\n.wrapper {\n    min-height: 100%;\n    height: 100%;\n    margin: 0 auto -155px; /* the bottom margin is the negative value of the footer's height */\n}\n.footer, .push {\n    height: 155px; /* .push must be the same height as .footer */\n}\n\n/*.row.display-flex {\n  display: flex;\n  flex-wrap: wrap;\n}\n.thumbnail {\n  height: 100%;\n}*/\n\n"
  },
  {
    "path": "src/web/templates/web/base.html",
    "content": "<!DOCTYPE html>\n<html>\n<head>\n\t<meta charset=\"UTF-8\">\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n    <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge,chrome=1\">\n    <title>{% block title %}Movies{% endblock title %}</title>\n    {% load staticfiles %}\n\n\t<link rel=\"stylesheet\" type=\"text/css\" href=\"{% static 'web/css/bootstrap.min.css'%}\">\n\t<link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css' >\n    <link href='http://fonts.googleapis.com/css?family=Open+Sans:400,300,700' rel='stylesheet' type='text/css'>\n    <link rel='stylesheet' href='{% static \"web/css/base.css\" %}' />\n\n    <style type=\"text/css\">\n        .thumbnail p, .thumbnail h4 {\n            white-space: nowrap;\n            text-overflow: ellipsis;\n            overflow: hidden;\n            }\n        .star-rating {\n            line-height:32px;\n            font-size:1.25em;\n            }\n\n.star-rating .fa-star{color: yellow;}\n        \n    </style>\n</head>\n<body>\n\t<nav class=\"navbar navbar-inverse\">\n                <div class=\"container-fluid\">\n\n                    <!-- Header -->\n                    <div class=\"navbar-header\">\n                        <button type=\"button\" class=\"navbar-toggle\" data-toggle=\"collapse\" data-target=\"#topNavBar\">\n                            <span class=\"icon-bar\"></span>\n                            <span class=\"icon-bar\"></span>\n                            <span class=\"icon-bar\"></span>\n                        </button>\n                        <a class=\"navbar-brand\" href=\"\">Movies</a>\n                    </div>\n\n                    <!-- Items -->\n                    <div class=\"collapse navbar-collapse\" id=\"topNavBar\">\n                        <ul class=\"nav navbar-nav \">\n                            \n                            <li><a href=\"{% url 'index' %}\">&nbsp; Home</a></li>\n                 \n\t\t\t\t\t\t</ul>\n\t\t\t\t\t\n                        <ul class=\"nav navbar-nav navbar-right\">\n                         {% if not request.user.is_authenticated %}\n                            <li>\n                                <a href=\"{% url 'signup' %}\">\n                                    <span aria-hidden=\"true\"></span>&nbsp; \n                                    SignUp\n                                </a>\n                            </li>\n                            <li>\n                                <a href=\"{% url 'login' %}\">\n                                    <span aria-hidden=\"true\"></span>&nbsp; Login\n                                </a>\n                            </li>\n                        {% else %}\n                            <li>\n                                <a href=\"{% url 'logout' %}\">\n                                    <span class=\"glyphicon glyphicon-off\" aria-hidden=\"true\"></span>&nbsp;Logout \n                                </a>\n                            </li>\n                        {% endif %}\n                        </ul>\n                    </div>\n\n                </div>\n\n    </nav>\n</div>  \n    {% block body %}\n    {% endblock %}\n     <nav class=\"navbar navbar-bottom\">                   \n    <footer class=\"page-footer font-small\">\n        <hr>\n          <div class=\"text-center center-block\">\n            <br />\n                <a href=\"https://www.facebook.com/profile.php?id=100004918600612\"><i id=\"social-fb\" class=\"fa fa-facebook-square fa-3x social\"></i></a>\n                <a href=\"https://twitter.com/asif536\"><i id=\"social-tw\" class=\"fa fa-twitter-square fa-3x social\"></i></a>\n                <a href=\"https://www.linkedin.com/in/mohd-asif-984a35121/\"><i class=\"fa fa-linkedin-square fa-3x social\"></i></a>\n                <a href=\"https://github.com/asif536\"><i id=\"social-git\"class=\"fa fa-github-square fa-3x\"></i></a>\n        </div>\n        <hr>\n        <div class=\"footer-copyright text-center py-3\">© 2018 Copyright:\n        <a href=\"#\"> MohdAsif</a>\n    </div>\n\n    </footer>\n    </nav>\n\t<script type=\"text/javascript\" src=\"{%static 'web/js/jquery.min.js'%}\">\n\t</script>\n\n\t<script type=\"text/javascript\" src=\"{%static 'web/js/bootstrap.min.js'%}\">\n\t</script>\n    <script type=\"text/javascript\">\n    var $star_rating = $('.star-rating .fa');\n\n    var SetRatingStar = function() {\n        return $star_rating.each(function() {\n        if (parseInt($star_rating.siblings('input.rating-value').val()) >= parseInt($(this).data('rating'))) {\n            return $(this).removeClass('fa-star-o').addClass('fa-star');\n        } else {\n        return $(this).removeClass('fa-star').addClass('fa-star-o');\n        }\n        });\n        };\n\n    $star_rating.on('click', function() {\n    $star_rating.siblings('input.rating-value').val($(this).data('rating'));\n    return SetRatingStar();\n    });\n\n    SetRatingStar();\n    $(document).ready(function() {\n\n    });\n        \n</script>\n<script type=\"text/javascript\">\n    function validateForm(){\n    var x = document.forms[\"ratingForm\"][\"rating\"].value;\n    if(x==\"0\"){\n        alert(\"Invalid Input\");\n        return false;\n    }\n    }\n</script>\n\n</body>\n</html>"
  },
  {
    "path": "src/web/templates/web/detail.html",
    "content": "{% extends 'web/base.html'%}\n{% block title %}{{movies.title}}{% endblock %}\n\n{% block body %}\n\n\n<div class=\"container-fluid col-sm-offset-1\">\n\n    <div class=\"row\">\n\n        <!-- Left Movie Info -->\n        <div class=\"col-sm-2 col-md-3\">\n            <div class=\"panel panel-default\">\n                <div class=\"panel-body\">\n                    <a href=\"#\">                            \n                        <img src=\"{{ movies.movie_logo.url}}\" class=\"img-responsive\">\n                    </a>\n                    <h2></h2>\n                </div>\n            </div>\n        </div>\n        <!-- Right Movie Info -->\n        <div class=\"col-sm-offset-1 col-sm-4 col-md-4\">\n            <h1>{{movies.title}}</h1>\n            <h3><small>{{movies.genre}}</small></h3>\n        \t<h1><small>Have you watch ?</small></h1>\n            <h3><small>Please rate to get recommendation </small></h3>\n            {% if messages %}\n            <ul class=\"messages\">\n            {% for message in messages %}\n                <li{% if message.tags %} class=\"{{ message.tags }}\"{% endif %}>{{ message }}</li>\n            {% endfor %}\n            </ul>\n            {% endif %}\n        <div class=\"col-sm-offset-0 col-sm-8\">\n            <form class=\"form-horizontal\" role=\"search\" method=\"post\" action=\"{% url 'detail' movies.id %}\" onsubmit=\"return validateForm()\"  name=\"ratingForm\">\n            <div class=\"form-group\">\n            <div class=\"input-group\"> \n             <div class=\"row\">\n            <div class=\"col-lg-12\">\n                  <div class=\"star-rating\">\n                    <span class=\"fa fa-star-o\" data-rating=\"1\"></span>\n                    <span class=\"fa fa-star-o\" data-rating=\"2\"></span>\n                    <span class=\"fa fa-star-o\" data-rating=\"3\"></span>\n                    <span class=\"fa fa-star-o\" data-rating=\"4\"></span>\n                    <span class=\"fa fa-star-o\" data-rating=\"5\"></span>\n               <input type=\"hidden\" name=\"rating\" class=\"rating-value\" value=\"0\" >\n                {% csrf_token %}\n\n                </div>\n            </div>\n            </div>\n            <input type=\"submit\" class=\"btn btn-info\" value=\"submit\">\n                \n\n         </div>\n         </div>\n        </form>\n    \n        </div>\n    </div>\t\n\n\n    </div>\n</div>\n\n{% endblock %}"
  },
  {
    "path": "src/web/templates/web/form_template.html",
    "content": "{% for field in form %}\n    <div class=\"form-group\">\n        <div class=\"col-sm-offset-2 col-sm-12\">\n            <span class=\"text-danger small\">{{ field.errors }}</span>\n        </div>\n        <label class=\"control-label col-sm-2\" for=\"movie_title\">{{ field.label_tag }}</label>\n        <div class=\"col-sm-10\">{{ field }}</div>\n    </div>\n{% endfor %}"
  },
  {
    "path": "src/web/templates/web/list.html",
    "content": "{% extends 'web/base.html'%}\n{% block body %}\n\n<div class=\"container\">\n    <div class=\"col-xs-6 col-xs-offset-3\">\n    \t<form class=\"form-horizontal\" role=\"search\" method=\"get\" action=''>\n         <div class=\"form-group\">\n         <div class=\"input-group\">\t\n            <input type=\"text\" class=\"form-control input-lg \" name=\"q\" value=\"{{ request.GET.q }}\" placeholder= \"Search Movies \"/>\n            <span class='input-group-btn'>\n\n             <button class='btn btn-info btn-lg' type='submit'>Search\n             </button>\n         </span>\n        </div>\n     </div>\n   </form>\n\n </div>\n</div>  \n    {% if messages %}\n            <ul class=\"messages\">\n            {% for message in messages %}\n                <li{% if message.tags %} class=\"{{ message.tags }}\"{% endif %} >{{ message }}</li>\n            {% endfor %}\n            </ul>\n    {% endif %}\n    <div class=\"container-fluid\">\n    <div class=\"row\">\n        <div class=\"col-sm-2 col-md-3\">\n\t\t<h1>Movies List</h1>\n        </div>\n        <div class=\"col-xs-offset-9  mt-3\">\n        <a href=\"{% url 'recommend' %}\" class=\"btn\"><strong><h2>Get Recommendation</h2></strong></a>\n        </div>\n    </div>\n\t</div>\n\t<div class=\"container-fluid\">\n    \n    <!-- Movie list -->\n    <div class=\"row\">\n            {% if movies %}\n            {% for movie in movies %}\n                <div class=\"col-sm-2 col-md-2 \">\n                    <div class=\"thumbnail\">\n                        <h4>{{movie.title}}</h4>\n                        <a href=\"{% url 'detail' movie.id %}\">\n                            <img src=\"{{ movie.movie_logo.url}}\" class=\"img-responsive\">\n                        </a>\n                        <h5>{{movie.genre}}</h5>\n                        <div class=\"caption\">\n\n                            <!-- View Details -->\n                            <a href=\"{% url 'detail' movie.id %}\" class=\"btn btn-primary btn-sm\" role=\"button\">Give Rating</a>\n\n                                        \n                        </div>\n                    </div>\n                </div>\n                {% endfor %}\n                {% endif %}\n        </div>\n    \n</div>\n\n{% endblock %}"
  },
  {
    "path": "src/web/templates/web/login.html",
    "content": "{% extends 'web/base.html'%}\n{% block title %}Log In{% endblock %}\n\n{% block body %}\n<div class=\"container-fluid\">\n\n    <div class=\"row\">\n        <div class=\"col-sm-12 col-md-6 col-md-offset-3\">\n            <div class=\"panel panel-default\">\n                <div class=\"panel-body\">\n                    <h3>Log In</h3>\n                    {% if error_message %}\n                        <p><strong>{{ error_message }}</strong></p>\n                    {% endif %}\n                    <form class=\"form-horizontal\" role=\"form\" action=\"#\" method=\"post\" enctype=\"multipart/form-data\">\n                        {% csrf_token %}\n                        <div class=\"form-group\">\n                            <label class=\"control-label col-sm-2\" for=\"id_username\">\n                                Username:\n                            </label>\n                            <div class=\"col-sm-10\">\n                                <input id=\"id_username\" maxlength=\"30\" name=\"username\" type=\"text\">\n                            </div> \n                        </div>\n                        <div class=\"form-group\">\n                            <label class=\"control-label col-sm-2\" for=\"id_password\">\n                                Password:\n                            </label>\n                            <div class=\"col-sm-10\">\n                                <input id=\"id_password\" maxlength=\"30\" name=\"password\" type=\"password\">\n                            </div>\n                        </div>\n                        <div class=\"form-group\">\n                            <div class=\"col-sm-offset-2 col-sm-10\">\n                                <button type=\"submit\" class=\"btn btn-success\">Submit</button>\n                            </div>\n                        </div>\n                    </form>\n                </div>\n                <div class=\"panel-footer\">\n                    Don't have an account? <a href=\"{% url 'signup' %}\">Click here</a> to register.\n                </div>\n            </div>\n        </div>\n    </div>\n\n</div>\n{% endblock %}"
  },
  {
    "path": "src/web/templates/web/recommend.html",
    "content": "{% extends 'web/base.html'%}\n{% block title %}Recommendations{% endblock %}\n{% block body %}\n\n<div class=\"container-fluid\">\n\t<h2>Recommendations for You </h2>\n</div>\n\n\n\t<div class=\"container-fluid\">\n    \n    <!-- Movie list -->\n    <div class=\"row\">\n            {% if movie_list %}\n            {% for movie in movie_list %}\n                <div class=\"col-sm-2 col-md-2 \">\n                    <div class=\"thumbnail\">\n                        <h4>{{movie.title}}</h4>\n                        <a href=\"{% url 'detail' movie.id %}\">\n                            <img src=\"{{ movie.movie_logo.url}}\" class=\"img-responsive\">\n                        </a>\n                        <h5>{{movie.genre}}</h5>\n                        <div class=\"caption\">\n\n                            <!-- View Details -->\n                            <a href=\"{% url 'detail' movie.id %}\" class=\"btn btn-primary btn-sm\" role=\"button\">Give Rating</a>\n\n                                        \n                        </div>\n                    </div>\n                </div>\n                {% endfor %}\n                {% endif %}\n        </div>\n    \n</div>\n\n{% endblock %}"
  },
  {
    "path": "src/web/templates/web/signUp.html",
    "content": "{% extends 'web/base.html'%}\n{% block title %}Register{% endblock %}\n{% block body %}\n<div class=\"container-fluid\">\n\n    <div class=\"row\">\n        <div class=\"col-sm-10 col-md-6 col-md-offset-3\">\n            <div class=\"panel panel-default\">\n                <div class=\"panel-body\">\n                    <h3>Register for an Account</h3>\n                    {% if error_message %}\n                        <p><strong>{{ error_message }}</strong></p>\n                    {% endif %}\n                    <form class=\"form-horizontal\" role=\"form\" action=\"\" method=\"post\" enctype=\"multipart/form-data\">\n                        {% csrf_token %}\n                        {% include 'web/form_template.html' %}\n                        <div class=\"form-group\">\n                            <div class=\"col-sm-offset-2 col-sm-10\">\n                                <button type=\"submit\" class=\"btn btn-success\">Submit</button>\n                            </div>\n                        </div>\n                    </form>\n                </div>\n                <div class=\"panel-footer\">\n                    Already have an account? <a href=\"{% url 'login' %}\">Click here</a> to log in.\n                </div>\n            </div>\n        </div>\n    </div>\n\n</div>\n\n{% endblock %}"
  },
  {
    "path": "src/web/tests.py",
    "content": "from django.test import TestCase\n\n# Create your tests here.\n"
  },
  {
    "path": "src/web/urls.py",
    "content": "from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n    path('', views.index, name='index'),\n    path('<int:movie_id>/',views.detail ,name='detail'),\n    path('signup/',views.signUp,name='signup'),\n    path('login/',views.Login,name='login'),\n    path('logout/',views.Logout,name='logout'),\n    path('recommend/',views.recommend,name='recommend')\n]"
  },
  {
    "path": "src/web/views.py",
    "content": "from django.contrib.auth import authenticate, login\nfrom django.contrib.auth import logout\nfrom django.shortcuts import render,get_object_or_404,redirect\nfrom django.db.models import Q\nfrom django.http import Http404\nfrom .models import Movie,Myrating\nfrom django.contrib import messages\nfrom .forms import UserForm\nfrom django.db.models import Case, When\nfrom .recommendation import Myrecommend\nimport numpy as np \nimport pandas as pd\n\n\n# for recommendation\ndef recommend(request):\n\tif not request.user.is_authenticated:\n\t\treturn redirect(\"login\")\n\tif not request.user.is_active:\n\t\traise Http404\n\tdf=pd.DataFrame(list(Myrating.objects.all().values()))\n\tnu=df.user_id.unique().shape[0]\n\tcurrent_user_id= request.user.id\n\t# if new user not rated any movie\n\tif current_user_id>nu:\n\t\tmovie=Movie.objects.get(id=15)\n\t\tq=Myrating(user=request.user,movie=movie,rating=0)\n\t\tq.save()\n\n\tprint(\"Current user id: \",current_user_id)\n\tprediction_matrix,Ymean = Myrecommend()\n\tmy_predictions = prediction_matrix[:,current_user_id-1]+Ymean.flatten()\n\tpred_idxs_sorted = np.argsort(my_predictions)\n\tpred_idxs_sorted[:] = pred_idxs_sorted[::-1]\n\tpred_idxs_sorted=pred_idxs_sorted+1\n\tprint(pred_idxs_sorted)\n\tpreserved = Case(*[When(pk=pk, then=pos) for pos, pk in enumerate(pred_idxs_sorted)])\n\tmovie_list=list(Movie.objects.filter(id__in = pred_idxs_sorted,).order_by(preserved)[:10])\n\treturn render(request,'web/recommend.html',{'movie_list':movie_list})\n\n\n# List view\ndef index(request):\n\tmovies = Movie.objects.all()\n\tquery  = request.GET.get('q')\n\tif query:\n\t\tmovies = Movie.objects.filter(Q(title__icontains=query)).distinct()\n\t\treturn render(request,'web/list.html',{'movies':movies})\n\treturn render(request,'web/list.html',{'movies':movies})\n\n\n# detail view\ndef detail(request,movie_id):\n\tif not request.user.is_authenticated:\n\t\treturn redirect(\"login\")\n\tif not request.user.is_active:\n\t\traise Http404\n\tmovies = get_object_or_404(Movie,id=movie_id)\n\t#for rating\n\tif request.method == \"POST\":\n\t\trate = request.POST['rating']\n\t\tratingObject = Myrating()\n\t\tratingObject.user   = request.user\n\t\tratingObject.movie  = movies\n\t\tratingObject.rating = rate\n\t\tratingObject.save()\n\t\tmessages.success(request,\"Your Rating is submited \")\n\t\treturn redirect(\"index\")\n\treturn render(request,'web/detail.html',{'movies':movies})\n\n\n# Register user\ndef signUp(request):\n\tform =UserForm(request.POST or None)\n\tif form.is_valid():\n\t\tuser      = form.save(commit=False)\n\t\tusername  =\tform.cleaned_data['username']\n\t\tpassword  = form.cleaned_data['password']\n\t\tuser.set_password(password)\n\t\tuser.save()\n\t\tuser = authenticate(username=username,password=password)\n\t\tif user is not None:\n\t\t\tif user.is_active:\n\t\t\t\tlogin(request,user)\n\t\t\t\treturn redirect(\"index\")\n\tcontext ={\n\t\t'form':form\n\t}\n\treturn render(request,'web/signUp.html',context)\t\t\t\t\n\n\n# Login User\ndef Login(request):\n\tif request.method==\"POST\":\n\t\tusername = request.POST['username']\n\t\tpassword = request.POST['password']\n\t\tuser     = authenticate(username=username,password=password)\n\t\tif user is not None:\n\t\t\tif user.is_active:\n\t\t\t\tlogin(request,user)\n\t\t\t\treturn redirect(\"index\")\n\t\t\telse:\n\t\t\t\treturn render(request,'web/login.html',{'error_message':'Your account disable'})\n\t\telse:\n\t\t\treturn render(request,'web/login.html',{'error_message': 'Invalid Login'})\n\treturn render(request,'web/login.html')\n\n#Logout user\ndef Logout(request):\n\tlogout(request)\n\treturn redirect(\"login\")\n\n\n\n\n"
  }
]