Spaces:
Runtime error

File size: 6,661 Bytes
63bcd5a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# # api/services.py

# import pandas as pd

# from src.similarity_engine import find_similar_projects
# from src.preprocessing import extract_features


# # =====================================================
# # Main Analyze Service
# # =====================================================
# def analyze_project(
#     title: str,
#     description: str,
#     abstract: str = "",
#     features=None,
#     top_k: int = 5
# ):
#     """
#     Full project analysis service
#     """

#     if features is None:
#         features = []

#     # ---------------------------------------------
#     # Build text for auto feature extraction
#     # ---------------------------------------------
#     full_text = f"{title}. {abstract}. {description}"

#     auto_features = extract_features(full_text)

#     # merge manual + auto
#     merged = []
#     seen = set()

#     for item in features + auto_features:
#         val = str(item).strip().lower()

#         if val and val not in seen:
#             seen.add(val)
#             merged.append(val)

#     # ---------------------------------------------
#     # Run similarity engine
#     # ---------------------------------------------
#     results = find_similar_projects(
#         title=title,
#         description=f"{abstract} {description}",
#         features=merged,
#         top_k=top_k
#     )

#     # ---------------------------------------------
#     # Convert dataframe to json records
#     # ---------------------------------------------
#     if isinstance(results, pd.DataFrame):
#         rows = results.to_dict(orient="records")
#     else:
#         rows = []

#     return {
#         "extracted_features": merged,
#         "results": rows
#     }


# api/services.py

# import pandas as pd

# from src.similarity_model import find_similar_projects
# from src.similarity_model import extract_features


# # =====================================================
# # Main Analyze Service
# # =====================================================
# def analyze_project(
#     title: str,
#     description: str,
#     abstract: str = "",
#     features=None,
#     top_k: int = 5
# ):
#     """
#     Final clean API response
#     Returns only user-needed metrics
#     """

#     if features is None:
#         features = []

#     # -------------------------------------------------
#     # Build full text for automatic feature extraction
#     # -------------------------------------------------
#     full_text = f"{title}. {abstract}. {description}"

#     auto_features = extract_features(full_text)

#     # -------------------------------------------------
#     # Merge manual + extracted features
#     # -------------------------------------------------
#     merged = []
#     seen = set()

#     for item in features + auto_features:
#         val = str(item).strip().lower()

#         if val and val not in seen:
#             seen.add(val)
#             merged.append(val)

#     # -------------------------------------------------
#     # Run similarity model
#     # -------------------------------------------------
#     results = find_similar_projects(
#         title=title,
#         description=f"{abstract} {description}",
#         features=merged,
#         top_k=top_k
#     )

#     # -------------------------------------------------
#     # No results found
#     # -------------------------------------------------
#     if not isinstance(results, pd.DataFrame) or len(results) == 0:
#         return {
#             "message": "No similar projects found",
#             "extracted_features": merged
#         }

#     # -------------------------------------------------
#     # Take top matched project only
#     # -------------------------------------------------
#     top = results.iloc[0]

#     return {
#         "extracted_features": merged,

#         "matched_features": top.get(
#             "matched_features", []
#         ),

#         "unique_features": top.get(
#             "unique_query_features", []
#         ),

#         "hybrid_similarity": round(
#             float(top.get("hybrid_score", 0)),
#             4
#         ),

#         "final_originality_score": round(
#             float(top.get("originality_score", 0)),
#             4
#         )
#     }

import pandas as pd
from fastapi import HTTPException

from src.similarity_model import find_similar_projects
from src.similarity_model import extract_features


def analyze_project(
    title: str,
    description: str,
    abstract: str = "",
    features=None,
    top_k: int = 5
):

    if features is None:
        features = []

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

    auto_features = extract_features(full_text)

    merged = []
    seen = set()

    for item in features + auto_features:
        val = str(item).strip().lower()

        if val and val not in seen:
            seen.add(val)
            merged.append(val)

    results = find_similar_projects(
        title=title,
        description=f"{abstract} {description}",
        features=merged,
        top_k=top_k
    )

    if not isinstance(results, pd.DataFrame) or len(results) == 0:
        return {
            "message": "No similar projects found",
            "extracted_features": merged
        }

    # -----------------------------------
    # رجع Top K كله
    # -----------------------------------
    top_projects = []

    for _, row in results.iterrows():
        top_projects.append({
            "project_title": row.get("project_title", ""),
            "matched_features": row.get("matched_features", []),
            "unique_features": row.get("unique_query_features", []),
            "similarity_score": round(float(row.get("hybrid_score", 0)), 4),
            "final_originality_score": round(float(row.get("originality_score", 0)), 4)
        })

    return {
        "extracted_features": merged,
        "top_similar_projects": top_projects
    }


def chat_with_llm(user_id: str, message: str):
    try:
        from src.recommendation_engine.chatbot_engine import chatbot
        from src.recommendation_engine.llm_client import LLMProviderError
    except Exception as exc:
        raise HTTPException(
            status_code=503,
            detail=f"LLM service could not start: {exc}"
        )

    try:
        response = chatbot(
            user_id=user_id,
            user_input=message
        )
    except LLMProviderError as exc:
        raise HTTPException(
            status_code=exc.status_code,
            detail=exc.message
        )

    return {
        "user_id": user_id,
        "response": response
    }