PageRenderTime 54ms CodeModel.GetById 30ms RepoModel.GetById 1ms app.codeStats 0ms

/gnowsys-ndf/gnowsys_ndf/ndf/management/commands/create_theme_topic_hierarchy.py

https://gitlab.com/g66shivam/gstudio
Python | 344 lines | 324 code | 11 blank | 9 comment | 6 complexity | 0dff6066446fa3784ca72757899bbb05 MD5 | raw file
  1. ''' -- imports from python libraries -- '''
  2. import os
  3. import csv
  4. import json
  5. import ast
  6. import datetime
  7. import time
  8. ''' imports from installed packages '''
  9. from django.core.management.base import BaseCommand, CommandError
  10. # from django_mongokit import get_database
  11. from django.template.defaultfilters import slugify
  12. from gnowsys_ndf.ndf.org2any import org2html
  13. from gnowsys_ndf.ndf.views.methods import create_gattribute
  14. # from mongokit import IS
  15. try:
  16. from bson import ObjectId
  17. except ImportError: # old pymongo
  18. from pymongo.objectid import ObjectId
  19. ''' imports from application folders/files '''
  20. from gnowsys_ndf.ndf.models import *
  21. ###################################################################
  22. SCHEMA_ROOT = os.path.join( os.path.dirname(__file__), "schema_files")
  23. # collection = get_database()[Node.collection_name]
  24. theme_gst = node_collection.one({'_type': 'GSystemType', 'name': 'Theme' })
  25. theme_item_gst = node_collection.one({'_type': 'GSystemType', 'name': 'theme_item' })
  26. topic_gst = node_collection.one({'_type': 'GSystemType', 'name': 'Topic'})
  27. home_group = node_collection.one({'_type': 'Group', 'name': 'home'})
  28. home_group_id = home_group._id
  29. curricular_at = node_collection.one({'_type': 'AttributeType', 'name': u'curricular'})
  30. alignment_at = node_collection.one({'_type': 'AttributeType', 'name': u'educationalalignment'})
  31. nroer_team_id = 1
  32. log_list = [] # To hold intermediate errors and logs
  33. log_list.append("\n######### Script run on : " + time.strftime("%c") + " #########\n############################################################\n")
  34. # utility function
  35. def create_user_nroer_team():
  36. '''
  37. Check for the user: "nroer_team". If it doesn't exists, create one.
  38. '''
  39. global nroer_team_id
  40. if User.objects.filter(username="nroer_team"):
  41. nroer_team_id = get_user_id("nroer_team")
  42. else:
  43. info_message = "\n- Creating super user: 'nroer_team': "
  44. user = User.objects.create_superuser(username='nroer_team', password='nroer_team', email='nroer_team@example.com')
  45. nroer_team_id = user.id
  46. info_message += "\n- Created super user with following creadentials: "
  47. info_message += "\n\n\tusername = 'nroer_team', \n\tpassword = 'nroer_team', \n\temail = 'nroer_team@example.com', \n\tid = '" + str(nroer_team_id) + "'"
  48. print info_message
  49. log_list.append(info_message)
  50. def get_user_id(user_name):
  51. '''
  52. Takes the "user name" as an argument and returns:
  53. - django "use id" as a response.
  54. else
  55. - returns False.
  56. '''
  57. try:
  58. user_obj = User.objects.get(username=user_name)
  59. return int(user_obj.id)
  60. except Exception as e:
  61. error_message = e + "\n!! for username: " + user_name
  62. print error_message
  63. log_list.append(str(error_message))
  64. return False
  65. class Command(BaseCommand):
  66. help = "\
  67. Creating themes topic hierarchy\
  68. Schema for CSV has to be as follows:\
  69. column 1: CR/XCR\
  70. column 2: featured\
  71. column 3: alignment\
  72. column 4: content_org for topic\
  73. column 5: Theme/Collection\
  74. column 6: Theme-item (sub-theme)\
  75. column ... : ... (sub-theme)\
  76. column n-1: Theme-item (sub-theme)\
  77. column n: Topic\
  78. "
  79. def handle(self, *args, **options):
  80. try:
  81. for file_name in args:
  82. file_path = os.path.join(SCHEMA_ROOT, file_name)
  83. if os.path.exists(file_path):
  84. info_message = "\n- CSV File (" + file_path + ") found!!!"
  85. print info_message
  86. log_list.append(str(info_message))
  87. else:
  88. info_message = "\n- CSV File (" + file_path + ") not found!!!"
  89. print info_message
  90. log_list.append(str(info_message))
  91. raise Exception(info_message)
  92. with open(file_path, 'rb') as f:
  93. # calling methid to get nroer_team_id
  94. create_user_nroer_team()
  95. reader = csv.reader(f)
  96. try:
  97. i = 1
  98. for index, each_row in enumerate(reader):
  99. each_row = [cell.strip() for cell in each_row]
  100. # print "\n each_row: ", each_row
  101. # print "\n descrp: ",descrp,"\n"
  102. create_theme_topic_hierarchy(each_row)
  103. i = i + 1
  104. print "\n", i ," rows successfully compiled"
  105. print " ======================================================="
  106. # if (i == 3):
  107. # break
  108. except csv.Error as e:
  109. sys.exit('file %s, line %d: %s' % (filename, reader.line_num, e))
  110. except Exception as e:
  111. print str(e)
  112. log_list.append(str(e))
  113. finally:
  114. if log_list:
  115. log_list.append("\n ============================================================ End of Iteration ============================================================\n")
  116. # print log_list
  117. log_file_name = args[0].rstrip("csv") + "log"
  118. log_file_path = os.path.join(SCHEMA_ROOT, log_file_name)
  119. # print log_file_path
  120. with open(log_file_path, 'a') as log_file:
  121. log_file.writelines(log_list)
  122. def create_theme_topic_hierarchy(row):
  123. """
  124. Args:
  125. row (list): each row of CSV
  126. e.g: ["CR/XCR", "featured", "alignment", "content_org", "Theme name", "theme item name", .., .., .... , "topic"]
  127. Returns:
  128. TYPE: Description
  129. """
  130. # print row
  131. language = row[0] # language field will get populated in this case.
  132. curricular = row[1] # CR or XCR
  133. featured = int(row[2]) # 0 or 1
  134. alignment = row[3] # like NCF
  135. content_org = row[4]
  136. theme_name = row[5] # theme-name like National Curriculum
  137. # topic_name = row[-1:]
  138. # --- Theme processing ---
  139. # fetching a theme node
  140. theme_node = node_collection.one({
  141. 'name': {'$regex': "^" + unicode(theme_name) + "$", '$options': 'i'},
  142. 'group_set': {'$in': [home_group_id]},
  143. 'member_of': theme_gst._id
  144. })
  145. # creating a new theme node:
  146. if not theme_node:
  147. theme_node = create_object(name=theme_name, member_of_id=theme_gst._id, featured=bool(featured), language=language)
  148. info_message = "- Created New Object : "+ str(theme_node.name) + "\n"
  149. print info_message
  150. log_list.append(str(info_message))
  151. # casting curricular field to bool:
  152. if curricular == "CR":
  153. curricular = True
  154. elif curricular == "XCR":
  155. curricular = False
  156. else: # needs to be confirm
  157. curricular = False
  158. # if theme_node already has curricular as attribute, it will update it's value
  159. # otherwise it will create a new attribute:
  160. ga_node = create_gattribute(theme_node._id, curricular_at, curricular)
  161. info_message = "- Created ga_node : "+ str(ga_node.name) + "\n"
  162. print info_message
  163. log_list.append(str(info_message))
  164. ga_node = create_gattribute(theme_node._id, alignment_at, unicode(alignment))
  165. info_message = "- Created ga_node : "+ str(ga_node.name) + "\n"
  166. print info_message
  167. log_list.append(str(info_message))
  168. # --- END of Theme processing ---
  169. # --- theme-item and topic processing ---
  170. # from 5th item or 4rd index of row there will be start of theme-item and topic(at last)
  171. theme_item_topic_list = row[6:]
  172. # do not entertain any blank values here:
  173. theme_item_topic_list = [i for i in theme_item_topic_list if i]
  174. # print theme_item_topic_list
  175. topic_name = theme_item_topic_list.pop() # Only 1 topic name, last item of row/list
  176. theme_item_list = theme_item_topic_list # list of only theme-item name's, after pop
  177. # to initiate with parent node:
  178. parent_node = theme_node
  179. # theme-item procesing ---
  180. for each_theme_item in theme_item_list:
  181. # print each_theme_item
  182. # fetching a theme-item node
  183. theme_item_node = node_collection.one({
  184. 'name': {'$regex': "^" + unicode(each_theme_item) + "$", '$options': 'i'},
  185. 'group_set': {'$in': [home_group_id]},
  186. 'member_of': {'$in': [theme_item_gst._id]},
  187. 'prior_node': {'$in': [parent_node._id]}
  188. })
  189. if not theme_item_node:
  190. theme_item_node = create_object(name=each_theme_item, member_of_id=theme_item_gst._id, prior_node_id=parent_node._id, language=language)
  191. info_message = "\n- Created theme-item : "+ str(theme_item_node.name) + "\n"
  192. print info_message
  193. log_list.append(str(info_message))
  194. else:
  195. info_message = "\n!! Theme Item : "+ str(theme_item_node.name) + " already exists!\n"
  196. print info_message
  197. log_list.append(str(info_message))
  198. # cheking for current theme-item's _id in collection_set of parent_node
  199. if not theme_item_node._id in parent_node.collection_set:
  200. add_to_collection_set(node_object=parent_node, id_to_be_added=theme_item_node._id)
  201. parent_node = theme_item_node
  202. # END of theme-item processing ---
  203. # topic processing ---
  204. # fetching a theme-item node
  205. topic_node = node_collection.one({
  206. 'name': {'$regex': "^" + unicode(topic_name) + "$", '$options': 'i'},
  207. 'group_set': {'$in': [home_group_id]},
  208. 'member_of': {'$in': [topic_gst._id]},
  209. 'prior_node': {'$in': [parent_node._id]}
  210. })
  211. if not topic_node:
  212. topic_node = create_object(name=topic_name, \
  213. member_of_id=topic_gst._id, \
  214. prior_node_id=parent_node._id, \
  215. content_org=content_org,\
  216. language=language)
  217. info_message = "\n--- Created topic : "+ str(topic_node.name) + "\n"
  218. print info_message
  219. log_list.append(str(info_message))
  220. else:
  221. info_message = "\n!! Topic : "+ str(topic_node.name) + " already exists!\n"
  222. print info_message
  223. log_list.append(str(info_message))
  224. # cheking for current theme-item's _id in collection_set of parent_node
  225. if not topic_node._id in parent_node.collection_set:
  226. add_to_collection_set(node_object=parent_node, id_to_be_added=topic_node._id)
  227. def create_object(name, member_of_id, prior_node_id=None, content_org=None, group_set_id=home_group_id, featured=None, language=('en', 'English')):
  228. node = node_collection.collection.GSystem()
  229. node.name = unicode(name)
  230. node.featured = featured
  231. node.language = eval(language)
  232. node.access_policy = u"PUBLIC"
  233. node.status = u"PUBLISHED"
  234. node.modified_by = nroer_team_id
  235. node.created_by = nroer_team_id
  236. node.contributors.append(nroer_team_id)
  237. node.group_set.append(group_set_id)
  238. node.member_of.append(member_of_id)
  239. if prior_node_id:
  240. node.prior_node.append(ObjectId(prior_node_id))
  241. if content_org:
  242. node.content_org = unicode(content_org)
  243. node.content = org2html(content_org, file_prefix=ObjectId().__str__())
  244. node.save()
  245. return node
  246. def add_to_collection_set(node_object, id_to_be_added):
  247. """Adds/updates a collection_set of object with provided object and id.
  248. Args:
  249. node_object (mongodb object)
  250. id_to_be_added (mongodb _id)
  251. Returns:
  252. updates an object but returns nothing
  253. """
  254. if not ObjectId(id_to_be_added) in node_object.collection_set and \
  255. node_object._id != id_to_be_added:
  256. node_collection.collection.update({
  257. '_id': node_object._id},
  258. {'$push': {'collection_set': ObjectId(id_to_be_added)} },
  259. upsert=False,
  260. multi=False
  261. )