forked from global-pulse/HunchWorks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodels.py
684 lines (490 loc) · 21 KB
/
models.py
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
#!/usr/bin/env python
import datetime
import numpy
from urlparse import urlparse
from django.db import models
from django.db.models import Q
from django.contrib.auth.models import User
from django.template import Template, Context
from django.db.models.signals import pre_save, post_save
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from hunchworks.signals import user_invited
from hunchworks import hunchworks_enums
from hunchworks import events
PRIVACY_CHOICES = (
(0, "Hidden"),
(1, "Closed"),
(2, "Open"))
PRIVACY_HELP_TEXT = "<br>".join([
"<strong>Hidden</strong>: only visible to explicitly invited users.",
"<strong>Closed</strong>: visible to all, but only invited users can contribute.",
"<strong>Open</strong>: available to any HunchWorks user."])
GROUP_STATUS_CHOICES = (
(0, "Invited"),
(1, "Accepted"),
(2, "Blocked"))
SUPPORT_CHOICES = (
(-2, "Strongly Refutes"),
(-1, "Mildly Refutes"),
(0, "Neutral"),
(1, "Mildly Supports"),
(2, "Strongly Supports"))
_support_values = zip(*SUPPORT_CHOICES)[0]
MIN_SUPPORT = min(_support_values)
MAX_SUPPORT = max(_support_values)
# The maximum possible standard deviation of a set of SUPPORT_CHOICES, for
# calculating the controversy ratio of a Hunch or HunchEvidence.
SUPPORT_MAX_DEVIATION = numpy.std([MIN_SUPPORT, MAX_SUPPORT])
POS_INF = float("inf")
NEG_INF = float("-inf")
SUPPORT_RANGES = (
(0, 0, "Neutral", "This hunch is not conclusively supported nor refuted by evidence."),
(1.1, POS_INF, "Strongly Supported", "This hunch is strongly supported by evidence, with <span>{{ confidence }} confidence.</span>"),
(NEG_INF, -1.1, "Strongly Refuted", "This hunch is strongly refuted by evidence, with <span>{{ confidence }} confidence.</span>"),
(0, 1.1, "Mildly Supported", "This hunch is supported by evidence, but only with <span>{{ confidence }} confidence.</span>"),
(-1.1, 0, "Mildly Refuted", "This hunch is refuted by evidence, but only with <span>{{ confidence }} confidence.</span>"))
CONTROVERSY_RANGES = (
(0, 0.2, "Uncontroversial", "This hunch is not controversial within the HunchWorks community."),
(0.2, 0.6, "Somewhat Controversial", "Some members of the HunchWorks community dispute this hunch."),
(0.6, 0.95, "Controversial", "Many members of the HunchWorks community dispute this hunch."),
(0.95, POS_INF, "Very Controversial", "This hunch is widely disputed within the HunchWorks community."))
# (days_to_consider, minimum_activity, text, verbose_text)
ACTIVITY_RANGES = (
(1, 2, "Very Active", "This hunch is being discussed by the HunchWorks community today."),
(7, 1, "Active", "This hunch is has been discussed by the HunchWorks community within a week."),
(None, 0, "Inactive", "This hunch is not being discussed or evaluated by the HunchWorks community."))
class UserProfile(models.Model, events.HasEvents):
user = models.ForeignKey(User, unique=True)
title = models.IntegerField(choices=hunchworks_enums.UserTitle.GetChoices(), default=0)
name = models.CharField(max_length=100)
email = models.EmailField(max_length=75)
privacy = models.IntegerField(choices=hunchworks_enums.PrivacyLevel.GetChoices(), default=0)
bio_text = models.TextField(blank=True)
phone = models.CharField(max_length=20, blank=True)
skype_name = models.CharField(max_length=30, blank=True)
website = models.CharField(max_length=100, blank=True)
profile_picture = models.ImageField(upload_to="profile_images", blank=True, null=True)
messenger_service = models.IntegerField(null=True, blank=True, choices=hunchworks_enums.MessangerServices.GetChoices(), default=0)
translation_language = models.ForeignKey('TranslationLanguage', default=0)
invitation = models.ForeignKey('Invitation', unique=True, null=True, blank=True)
connections = models.ManyToManyField('self', through='Connection', symmetrical=False, blank=True)
roles = models.ManyToManyField("Role", blank=True)
location_interests = models.ManyToManyField('Location', blank=True)
qualifications = models.ManyToManyField('Education', blank=True)
courses = models.ManyToManyField('Course', blank=True)
def __unicode__(self):
return self.name or self.user.username
@models.permalink
def get_absolute_url(self):
return ("profile", [self.pk])
def profile_picture_url(self):
if self.profile_picture:
return self.profile_picture.url
else:
return "http://www.clker.com/cliparts/5/9/4/c/12198090531909861341man%20silhouette.svg.hi.png"
@classmethod
def search(cls, query):
return cls.objects.filter(
Q(user__username__icontains=query) | Q(name__icontains=query))
def create_user(sender, instance, created, **kwargs):
if created: UserProfile.objects.create(user=instance)
post_save.connect(create_user, sender=User)
class Connection(models.Model):
user_profile = models.ForeignKey('UserProfile', related_name="outgoing_connections")
other_user_profile = models.ForeignKey('UserProfile', related_name="incoming_connections")
status = models.IntegerField(default=0)
def __unicode__(self):
return "%s -> %s" % (self.user_profile, self.other_user_profile)
@classmethod
def search(cls, term, user_profile=None):
return cls.objects.filter(user_profile=user_profile, other_user_profile__user__username__icontains=term)
class Hunch(models.Model, events.HasEvents):
creator = models.ForeignKey('UserProfile', related_name="created_hunches")
time_created = models.DateTimeField()
time_modified = models.DateTimeField()
title = models.CharField(max_length=160)
description = models.TextField(blank=True)
privacy = models.IntegerField(choices=PRIVACY_CHOICES, default=0, help_text=PRIVACY_HELP_TEXT)
location = models.ForeignKey('Location', null=True, blank=True)
evidences = models.ManyToManyField( 'Evidence', through='HunchEvidence', blank=True)
tags = models.ManyToManyField('Tag', blank=True)
user_profiles = models.ManyToManyField("UserProfile")
groups = models.ManyToManyField("Group")
class Meta:
verbose_name_plural = "hunches"
def __unicode__(self):
return self.title
def invite(self, invite_proxy, inviter, message):
obj = invite_proxy.content_object
if isinstance(obj, UserProfile):
self.user_profiles.add(obj)
user_invited.send(
sender=Hunch, instance=self,
inviter=inviter, invitee=obj,
message=message)
else:
raise NotImplementedError
@models.permalink
def get_absolute_url(self):
return ("hunch", [self.pk])
def save(self, *args, **kwargs):
now = datetime.datetime.today()
self.time_modified = now
# for new records.
if not self.id:
self.time_created = now
return super(Hunch, self).save(
*args, **kwargs)
def contributors(self):
"""
Return a QuerySet containing the UserProfiles which have contributed to
this hunch (i.e. they have added evidence or commented on it).
"""
user_profile_ids = set()
query_sets = [
Evidence.objects.filter(hunch=self),
Comment.objects.filter(Q(hunch_evidence=self) | Q(hunch=self))
]
for query_set in query_sets:
ids = query_set.values_list("creator_id", flat=True)
user_profile_ids.update(ids)
return UserProfile.objects.filter(id__in=user_profile_ids)
def get_support(self):
supports = map(HunchEvidence.get_support, self.hunchevidence_set.all())
return (sum(supports) / len(supports)) if any(supports) else 0
def get_support_range(self):
s = self.get_support()
for min_val, max_val, text, desc in SUPPORT_RANGES:
if (min_val <= s) and (max_val >= s):
return (text, desc)
return ("Unknown", "The support level of this hunch cannot be determined.")
def get_support_text(self):
return self.get_support_range()[0]
def get_verbose_support_text(self):
tmpl = self.get_support_range()[1]
return Template(tmpl).render(Context({
"confidence": self.get_confidence_text()
}))
def get_confidence(self):
return abs(self.get_support()) / MAX_SUPPORT
def get_confidence_text(self):
return unicode(int(round(self.get_confidence() * 100))) + "%"
def get_controversy(self):
choices = Vote.objects.filter(hunch_evidence__hunch=self).values_list("choice", flat=True)
return (numpy.std(choices) / SUPPORT_MAX_DEVIATION) if any(choices) else 0
def get_controversy_range(self):
s = self.get_controversy()
for min_val, max_val, text, desc in CONTROVERSY_RANGES:
if (min_val <= s) and (max_val >= s):
return (text, desc)
return ("Unknown", "The controversy level of this hunch cannot be determined.")
def get_controversy_text(self):
return self.get_controversy_range()[0]
def get_verbose_controversy_text(self):
return self.get_controversy_range()[1]
def activity_count(self, since_days=7):
since = datetime.datetime.now() -\
datetime.timedelta(days=since_days)
votes = Vote.objects.filter(
hunch_evidence__hunch=self,
time_updated__gt=since)
comments = Comment.objects.filter(
hunch_evidence__hunch=self,
time_posted__gt=since)
return votes.count() + comments.count()
def get_activity_range(self):
for days, min_activity, text, desc in ACTIVITY_RANGES:
if (days is None) or (self.activity_count(days) >= min_activity):
return (text, desc)
return ("Unknown", "The activity level of this hunch cannot be determined.")
def get_activity_text(self):
return self.get_activity_range()[0]
def get_verbose_activity_text(self):
return self.get_activity_range()[1]
@property
def privacy_text(self):
return self.get_privacy_display()
def is_editable_by(self, user):
"""Return True if this Hunch is editable by `user` (a Django auth user)."""
return (self.creator.user == user)
def is_viewable_by(self, user):
"""Return True if this Hunch is viewable by `user` (a Django auth user)."""
if self._is_hidden():
return (self.creator.user == user)
# Otherwise, if the hunch is OPEN or CLOSED, anyone (even anonymous) can
# view it. The only distinction between the levels is in the editing.
return True
def evidences_for(self):
return HunchEvidence.objects.filter(hunch=self, support_cache__gt=0).order_by("-confidence_cache")
def evidences_against(self):
return HunchEvidence.objects.filter(hunch=self, support_cache__lte=0).order_by("-confidence_cache")
def _is_hidden(self):
"""Return True if this Hunch is hidden."""
return (self.privacy == hunchworks_enums.PrivacyLevel.HIDDEN)
def member_count(self):
return self.user_profiles.all().count()
def evidence_count(self):
return self.evidences.all().count()
def comment_count(self):
return self.comment_set.count()
def contributor_count(self):
return self.contributors().count()
def get_related_hunches(self, limit=4):
return Hunch.objects.all()[:limit]
post_save.connect(
events.hunch_created,
sender=Hunch)
user_invited.connect(
events.user_invited_to_hunch,
sender=Hunch)
class Evidence(models.Model):
title = models.CharField(verbose_name="Short description", max_length=100, blank=True,
help_text="This should be a short summary of the evidence or what it contains")
time_created = models.DateTimeField()
time_modified = models.DateTimeField()
description = models.TextField(verbose_name="Further explanation", blank=True)
location = models.ForeignKey('Location', null=True, blank=True)
creator = models.ForeignKey('UserProfile')
link = models.CharField(max_length=255, blank=True)
upload = models.FileField(upload_to='evidence', blank=True, null=True)
tags = models.ManyToManyField('Tag', blank=True)
def __unicode__(self):
return self.title or self.description or self.link or self.pk
def type(self):
return "Link"
def short_link(self, max_length=32):
return urlparse(self.link).hostname
def save(self, *args, **kwargs):
now = datetime.datetime.today()
# for new records.
if not self.id:
self.time_created = now
self.time_modified = now
super(Evidence, self).save(*args, **kwargs)
@models.permalink
def get_absolute_url(self):
return ("evidence", [self.pk])
@classmethod
def search(cls, term, user_profile=None):
return cls.objects.filter(
Q(description__icontains=term) | Q(title__icontains=term))
class Group(models.Model):
name = models.CharField(max_length=100, unique=True)
abbreviation = models.CharField(max_length=10, null=True, blank=True)
description = models.TextField(blank=True, help_text="You can use HTML here.")
logo = models.ImageField(verbose_name="Group picture", upload_to="group_images", blank=True, null=True)
type = models.IntegerField(choices=hunchworks_enums.GroupType.GetChoices(), default=0)
privacy = models.IntegerField(choices=PRIVACY_CHOICES, default=0, help_text=PRIVACY_HELP_TEXT)
location = models.ForeignKey('Location', null=True, blank=True,
help_text="The location in the world where the group is located")
members = models.ManyToManyField('UserProfile', through='UserProfileGroup', null=True, blank=True)
def __unicode__(self):
return self.name
@models.permalink
def get_absolute_url(self):
return ("group", [self.pk])
def invite_to_hunch(self, sent_by, hunch):
hunch.groups.add(self)
def member_count(self):
return self.members.all().count()
def hunch_count(self):
return 0
@classmethod
def search(cls, query):
return cls.objects.filter(
Q(name__icontains=query))
class UserProfileGroup(models.Model):
user_profile = models.ForeignKey('UserProfile')
group = models.ForeignKey('Group')
status = models.IntegerField(choices=GROUP_STATUS_CHOICES, default=0)
def __unicode__(self):
return "<UserProfileGroup:%d>" % self.pk
class Attachment(models.Model):
type = models.IntegerField()
file_location = models.CharField(max_length=100) # TODO filefield
def __unicode__(self):
return "<Attachment:%d>" % self.pk
class Album(models.Model):
name = models.CharField(max_length=45)
evidences = models.ManyToManyField('Evidence')
def __unicode__(self):
return self.name
@models.permalink
def get_absolute_url(self):
return ("album", [self.pk])
class Education(models.Model):
school = models.CharField(max_length=255)
qualification = models.CharField(max_length=100)
start_date = models.DateField()
end_date = models.DateField(null=True, blank=True)
def __unicode__(self):
return "<Education:%d>" % self.pk
class Course(models.Model):
"""
An more informal educational course which does not fit neatly into the
Education model. (E.g. "Diploma from NYC underwater welding club".)
"""
name = models.CharField(max_length=45)
start_date = models.DateField()
end_date = models.DateField(null=True, blank=True)
class Meta:
verbose_name_plural = "classes"
def __unicode__(self):
return "<Course:%d>" % self.pk
class TranslationLanguage(models.Model):
name = models.CharField(unique=True, max_length=45)
def __unicode__(self):
return self.name
class Location(models.Model):
latitude = models.DecimalField(max_digits=9, decimal_places=6)
longitude = models.DecimalField(max_digits=9, decimal_places=6)
name = models.CharField(max_length=200, blank=True)
def __unicode__(self):
return self.name or "<Location:%d>" % self.pk
@classmethod
def search(cls, term, user_profile=None):
return cls.objects.filter(name__icontains=term)
class Tag(models.Model):
name = models.CharField(max_length=40)
def __unicode__(self):
return self.name
@classmethod
def search(cls, term, user_profile=None):
return cls.objects.filter(name__icontains=term)
@classmethod
def create_via_tokeninput(cls, value):
return cls.objects.create(name=value.strip())
class Role(models.Model):
group = models.ForeignKey('Group')
title = models.CharField(max_length=40)
start_date = models.DateField()
end_date = models.DateField(null=True, blank=True)
description = models.TextField(blank=True)
def __unicode__(self):
return self.title
class Language(models.Model):
name = models.CharField(unique=True, max_length=100)
def __unicode__(self):
return self.name
@classmethod
def search(cls, term, user_profile=None):
return cls.objects.filter(name__icontains=term)
class Invitation(models.Model):
email = models.CharField(max_length=100)
sent_by = models.ForeignKey('UserProfile', related_name="invitations")
hunch = models.ForeignKey('Hunch', null=True, blank=True)
def __unicode__(self):
return "%s to %s" % (self.email, self.hunch)
class Comment(models.Model):
creator = models.ForeignKey('UserProfile')
time_posted = models.DateTimeField()
text = models.TextField()
hunch = models.ForeignKey('Hunch', null=True, blank=True)
hunch_evidence = models.ForeignKey('HunchEvidence', null=True, blank=True)
@models.permalink
def get_absolute_base_url(self):
if self.hunch_evidence:
return ("hunch_evidence", [self.hunch_evidence.hunch.pk, self.hunch_evidence.evidence.pk])
elif self.hunch:
return ("hunch_comments", [self.hunch.pk])
def get_absolute_url(self):
return self.get_absolute_base_url() + ("#c%d" % self.pk)
def save(self, *args, **kwargs):
self.time_posted = datetime.datetime.today()
super(Comment, self).save(*args, **kwargs)
post_save.connect(
events.comment_posted,
sender=Comment)
class HunchEvidence(models.Model):
hunch = models.ForeignKey('Hunch')
evidence = models.ForeignKey('Evidence')
creator = models.ForeignKey('UserProfile')
support_cache = models.IntegerField(choices=SUPPORT_CHOICES, null=True)
confidence_cache = models.FloatField(null=True)
class Meta:
unique_together = ("hunch", "evidence")
@models.permalink
def get_absolute_url(self):
return ("hunch_evidence", [self.hunch.pk, self.evidence.pk])
def save(self, *args, **kwargs):
self.support_cache = self.get_support()
self.confidence_cache = self.get_controversy()
super(HunchEvidence, self).save(*args, **kwargs)
def get_support(self):
return self.vote_set.aggregate(models.Avg("choice"))["choice__avg"] or 0
def get_controversy(self):
choices = self.vote_set.values_list("choice", flat=True)
if len(choices):
return numpy.std(choices) / SUPPORT_MAX_DEVIATION
else:
return 0
post_save.connect(
events.evidence_attached,
sender=HunchEvidence)
class Vote(models.Model):
choice = models.IntegerField(choices=SUPPORT_CHOICES, default=None)
hunch_evidence = models.ForeignKey('HunchEvidence')
user_profile = models.ForeignKey('UserProfile')
time_updated = models.DateTimeField()
def save(self, *args, **kwargs):
self.time_updated = datetime.datetime.now()
return super(Vote, self).save(*args, **kwargs)
def update_hunch_evidence_caches(sender, instance, created, **kwargs):
instance.hunch_evidence.save()
post_save.connect(
update_hunch_evidence_caches,
sender=Vote)
class Bookmark(models.Model):
user_profile = models.ForeignKey('UserProfile')
#Generic foreign key
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
@classmethod
def bookmark_get_create(cls, object, user_profile):
try:
object_type = ContentType.objects.get_for_model(object)
bookmark = cls.objects.get(content_type=object_type.id, object_id=object.id, user_profile=user_profile)
return bookmark
except cls.DoesNotExist:
bookmark = cls.objects.create(content_object=object, user_profile=user_profile)
return bookmark
class InviteProxy(models.Model):
"""
This model exists solely to provide a generic foreign key to objects which
can be "invited" to things (e.g. to a hunch, to a group).
This is a hack, to allow us to use TokenField for invites. It would probably
be better to store this sort of thing in MongoDB, but we'd lose the implicit
integration, which is kind of the whole point.
"""
MODELS = [UserProfile, Group]
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey("content_type", "object_id")
# This field should be named "name_cache" (or something similar), but
# djTokeninput fetches the results using values_list("id", "name").
name = models.CharField(max_length=255)
def __unicode__(self):
return self.name
@classmethod
def search(cls, query):
return cls.objects.filter(
name__icontains=query)
@classmethod
def connect_signals(cls):
# Call _post_save every time one of cls.MODELS is saved.
for model in cls.MODELS:
post_save.connect(
cls._post_save,
sender=model)
@classmethod
def _post_save(cls, sender, instance, created, **kwargs):
# Ensure that we have an InviteProxy to instance.
obj, created = cls.objects.get_or_create(
content_type=ContentType.objects.get_for_model(instance),
object_id=instance.pk)
# Update our cached name.
obj.name = unicode(instance)
obj.save()
InviteProxy.connect_signals()