File size: 10,993 Bytes
63bcd5a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6459fd1
 
 
63bcd5a
6459fd1
 
63bcd5a
6459fd1
 
63bcd5a
6459fd1
 
63bcd5a
6459fd1
 
63bcd5a
6459fd1
 
63bcd5a
6459fd1
 
63bcd5a
6459fd1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63bcd5a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4552666
63bcd5a
 
 
 
 
 
 
4552666
63bcd5a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4552666
63bcd5a
 
 
4552666
809b701
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63bcd5a
 
 
4552666
63bcd5a
 
 
 
4552666
63bcd5a
 
 
 
 
 
 
4552666
63bcd5a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4552666
63bcd5a
 
 
 
 
 
 
 
809b701
 
 
 
 
63bcd5a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4552666
 
 
63bcd5a
 
 
 
 
 
 
 
4552666
 
 
63bcd5a
 
 
 
 
 
 
 
 
4552666
 
 
63bcd5a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4552666
 
 
63bcd5a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
809b701
63bcd5a
 
 
4552666
 
 
63bcd5a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
809b701
63bcd5a
 
 
809b701
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63bcd5a
 
 
 
 
 
809b701
63bcd5a
 
8081e10
 
63bcd5a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4552666
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
import logging
import re

from collections import Counter
from typing import Dict, Any, List
from functools import lru_cache
from difflib import get_close_matches

import pandas as pd

from src.similarity_model import (
    find_similar_projects,
    extract_features
)

from src.recommendation_engine.config import (
    SIMILARITY_TOP_K,
    MAX_FEATURES
)

logger = logging.getLogger(__name__)

DOMAIN_KEYWORDS = {
    "AI & Machine Learning": [
        "ai", "artificial intelligence", "machine learning", "ml", "deep learning",
        "neural network", "nlp", "computer vision"
    ],
    "Business & Finance": [
        "fintech", "finance", "bank", "payment", "crypto", "blockchain", "business", "trading"
    ],
    "Cloud & DevOps": [
        "cloud", "devops", "aws", "azure", "docker", "kubernetes", "infrastructure"
    ],
    "Cybersecurity": [
        "security", "cyber", "cybersecurity", "threat", "attack", "malware", "hacking"
    ],
    "Education": [
        "education", "school", "learning", "edtech", "student", "university", "academic"
    ],
    "Healthcare": [
        "hospital", "health", "medical", "healthcare", "clinic", "patient", "care"
    ],
    "IoT & Embedded Systems": [
        "iot", "embedded", "hardware", "sensor", "arduino", "raspberry", "smart home"
    ],
    "Web & Mobile Development": [
        "web", "mobile", "app", "ios", "android", "frontend", "backend", "fullstack", "website"
    ],
    "Data Science & Analytics": [
        "data", "analytics", "science", "big data", "dashboard", "statistics"
    ],
    "E-Commerce & Marketplaces": [
        "ecommerce", "shopping", "retail", "store", "marketplace", "shop"
    ],
    "Smart Systems": [
        "smart system", "automation", "smart city", "smart"
    ],
    "Networking & Communication": [
        "networking", "communication", "telecom", "5g", "network"
    ],
    "Game Development": [
        "game", "gaming", "unity", "unreal", "ar", "vr"
    ],
    "Others": [
        "general", "random", "anything", "any", "whatever", "surprise me", "mixed", "all", "open", "everything", "other"
    ]
}

def normalize(text: str) -> str:

    text = str(text).lower().strip()

    text = re.sub(r"[^a-z0-9\s]", " ", text)

    text = re.sub(r"\s+", " ", text).strip()

    return text

def clean_list(
    items: List[str],
    limit: int = 20
) -> List[str]:

    final = []

    seen = set()

    for item in items:

        val = normalize(item)

        if not val:
            continue

        if val not in seen:

            seen.add(val)

            final.append(val)

    return final[:limit]

def detect_domains(text: str) -> List[str]:

    text = normalize(text)

    detected = []

    words_in_text = set(text.split())

    for domain, words in DOMAIN_KEYWORDS.items():

        for w in words:

            
            if " " in w:

                if w in text:

                    detected.append(domain)
                    break

            
            else:

                if w in words_in_text:

                    detected.append(domain)
                    break

    return clean_list(detected, limit=3)

def extract_domain(text: str) -> str:

    if not text:
        return ""

    text = normalize(text)

    
    if text in ["ai", "ml"]:
        return "artificial intelligence"

    
    # Map normalized domain names to their original keys
    normalized_domains = {normalize(d): d for d in DOMAIN_KEYWORDS.keys()}
    if text in normalized_domains:
        return normalized_domains[text]

    # Check close matches against normalized domain names
    match_domain = get_close_matches(
        text,
        list(normalized_domains.keys()),
        n=1,
        cutoff=0.85
    )
    if match_domain:
        return normalized_domains[match_domain[0]]

    if text in DOMAIN_KEYWORDS:
        return text

    
    domains = detect_domains(text)

    if domains:

        
        for d in domains:

            if d != "general":
                return d

        return domains[0]

    
    all_words = []

    word_map = {}

    for domain, words in DOMAIN_KEYWORDS.items():

        for w in words:

            all_words.append(w)

            word_map[w] = domain

    match = get_close_matches(
        text,
        all_words,
        n=1,
        cutoff=0.75
    )

    if match:
        return word_map[match[0]]

    
    for domain, words in DOMAIN_KEYWORDS.items():

        for w in words:

            if text in w or w.startswith(text):

                return domain

    others_keywords = DOMAIN_KEYWORDS.get("Others", [])
    if any(ow in text for ow in others_keywords):
        return "Others"

    return ""

@lru_cache(maxsize=100)
def cached_similarity(
    title: str,
    description: str
):

    return find_similar_projects(
        title=title,
        description=description,
        top_k=SIMILARITY_TOP_K
    )

def extract_common_features(
    results: pd.DataFrame
) -> List[str]:

    counter = Counter()

    if not isinstance(results, pd.DataFrame):
        return []

    for _, row in results.iterrows():

        matches = row.get(
            "matched_features",
            []
        )

        for item in matches:

            if isinstance(item, dict):

                feat = item.get(
                    "feature_b",
                    ""
                )

                feat = normalize(feat)

                if feat:

                    counter[feat] += 1

    return [
        feat
        for feat, _
        in counter.most_common(12)
    ]

def extract_titles(
    results: pd.DataFrame
) -> List[str]:

    if not isinstance(results, pd.DataFrame):
        return []

    titles = [
        str(row.get("project_title", "")).strip()
        for _, row in results.iterrows()
        if row.get("project_title")
    ]

    return clean_list(titles, limit=10)

def build_architecture_hints(
    domains: List[str]
) -> List[str]:

    hints = []

    if "artificial intelligence" in domains:
        hints.extend([
            "AI inference pipeline",
            "Model prediction workflow",
            "Data preprocessing module"
        ])

    if "healthcare" in domains:
        hints.extend([
            "Emergency handling workflow",
            "Patient monitoring logic",
            "Medical alert system"
        ])

    if "security" in domains:
        hints.extend([
            "Threat detection pipeline",
            "Behavior anomaly analysis",
            "Risk monitoring engine"
        ])

    if "education" in domains:
        hints.extend([
            "Adaptive learning workflow",
            "Student performance analytics",
            "Recommendation engine"
        ])

    return clean_list(hints, limit=10)

def build_project_context(
    title: str,
    description: str,
    abstract: str = "",
    features: List[str] = None
) -> Dict[str, Any]:

    features = features or []

    logger.info("Building project context")

    full_text = (
        f"{title}. "
        f"{abstract}. "
        f"{description}"
    )

    
    
    
    domains = detect_domains(full_text)

    main_domain = (
        domains[0]
        if domains
        else "general"
    )

    
    
    
    auto_features = extract_features(
        full_text
    )

    user_features = clean_list(
        features + auto_features,
        MAX_FEATURES
    )

    
    
    
    try:

        results = cached_similarity(
            title,
            description
        )

    except Exception as e:

        logger.warning(
            f"Similarity failed: {e}"
        )

        results = None

    
    
    
    if (
        not isinstance(results, pd.DataFrame)
        or len(results) == 0
        or "message" in results.columns
    ):

        return {
            "project_title": title,
            "domain": main_domain,
            "domains": domains,
            "features": user_features,
            "similar_titles": [],
            "common_features": [],
            "unique_features": user_features,
            "architecture_hints": build_architecture_hints(domains),
            "originality_score": 99.0,
            "context_strength": 0.0
        }

    
    
    
    similar_titles = extract_titles(results)

    common_features = extract_common_features(
        results
    )

    unique_features = [
        f
        for f in user_features
        if f not in common_features
    ]

    hybrid_scores = results.get(
        "hybrid_score",
        pd.Series([0])
    )

    context_strength = float(
        hybrid_scores.mean()
    )

    return {
        "project_title": title,
        "domain": main_domain,
        "domains": domains,
        "features": user_features,
        "similar_titles": similar_titles,
        "common_features": common_features,
        "unique_features": unique_features,
        "architecture_hints": build_architecture_hints(domains),
        "originality_score": calibrate_originality(context_strength),
        "context_strength": round(context_strength, 4)
    }

def calibrate_originality(similarity: float) -> float:
    """
    Piecewise linear calibration curve mapping database similarity to originality percentage.
    - S <= 0.45: maps linearly to O in [85.0%, 99.0%]
    - S > 0.45: maps linearly to O in [5.0%, 85.0%]
    """
    s = max(0.0, min(1.0, float(similarity)))
    if s <= 0.45:
        originality = 99.0 - (s / 0.45) * 14.0
    else:
        originality = 85.0 - ((s - 0.45) / 0.55) * 80.0
    return round(originality, 2)




def build_domain_context(
    domain: str
) -> Dict[str, Any]:

    extracted = extract_domain(domain)

    if extracted and extracted.lower() != "others":
        domain_clean = extracted
    else:
        logger.info(
            f"[DOMAIN INFO] Using custom dynamic domain: {domain}"
        )

        domain_clean = normalize(domain)

    logger.info(
        f"Building domain context: {domain_clean}"
    )

    try:

        results = cached_similarity(
            domain_clean,
            domain_clean
        )

    except Exception as e:

        logger.warning(
            f"Domain similarity failed: {e}"
        )

        results = None

    if (
        not isinstance(results, pd.DataFrame)
        or len(results) == 0
        or "message" in results.columns
    ):

        return {
            "domain": domain_clean,
            "existing_titles": [],
            "common_features": [],
            "architecture_hints": build_architecture_hints([domain_clean]),
            "context_strength": 0.0
        }

    hybrid_scores = results.get(
        "hybrid_score",
        pd.Series([0])
    )

    return {
        "domain": domain_clean,
        "existing_titles": extract_titles(results),
        "common_features": extract_common_features(results),
        "architecture_hints": build_architecture_hints([domain_clean]),
        "context_strength": round(
            float(hybrid_scores.mean()),
            4
        )
    }