File size: 9,908 Bytes
d614256
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
export interface UserNode {
  displayName: string;
  username: string;
}

export interface ParseResult {
  relationships: Map<string, { following: UserNode[], followers: UserNode[] }>;
  allUsers: Map<string, UserNode>;
  logs: string[];
}

export function parseSocialData(text: string): ParseResult {
  const result: ParseResult = {
    relationships: new Map(),
    allUsers: new Map(),
    logs: [],
  };

  const addLog = (msg: string) => {
    result.logs.push(`[${new Date().toLocaleTimeString()}] ${msg}`);
  };

  // 1. Clean text
  let cleaned = text.replace(/[\u200B-\u200D\uFEFF]/g, ''); 
  cleaned = cleaned.replace(/\.{3,}/g, '\n'); 

  // Make sure headers are on their own lines
  cleaned = cleaned.replace(/(Following|Followers)(\d+)/gi, '\n$1\n$2\n');

  const rawLines = cleaned.split('\n').map(l => l.trim()).filter(l => l.length > 0);
  addLog(`Started parsing. Extracted ${rawLines.length} raw lines after cleanup.`);

  let currentSubject: string | null = null;
  let currentContext: 'following' | 'followers' | null = null;
  let lastParsedNode: UserNode | null = null;

  let i = 0;
  
  while (i < rawLines.length) {
    const line = rawLines[i];
    
    // Check if header
    if (/^(Following|Followers)$/i.test(line)) {
      const isFollowing = line.toLowerCase() === 'following';
      const newContext = isFollowing ? 'following' : 'followers';
      
      if (i + 1 < rawLines.length && /^\d+$/.test(rawLines[i+1])) {
          i++; // Skip the count line
      }
      
      if (lastParsedNode) {
          if (currentSubject !== lastParsedNode.username) {
              currentSubject = lastParsedNode.username;
              if (!result.relationships.has(currentSubject)) {
                  result.relationships.set(currentSubject, { following: [], followers: [] });
              }
              addLog(`New graph center identified: ${currentSubject} (Tracking ${newContext})`);
              
              // Remove the subject from the previous context's relationships
              for (const rels of result.relationships.values()) {
                  if (rels.following.length > 0 && rels.following[rels.following.length - 1].username === lastParsedNode.username) {
                      rels.following.pop();
                  }
                  if (rels.followers.length > 0 && rels.followers[rels.followers.length - 1].username === lastParsedNode.username) {
                      rels.followers.pop();
                  }
              }
          } else {
              addLog(`Switched context to: ${newContext} for ${currentSubject}`);
          }
      }
      
      currentContext = newContext;
      i++;
      continue;
    }
    
    // Ignore stray numbers
    if (/^\d+$/.test(line)) {
        i++;
        continue;
    }
    
    let displayName = "";
    let username = "";
    
    const nextLine = (i + 1 < rawLines.length) ? rawLines[i+1] : null;
    const nextIsHeaderOrNumber = nextLine && (/^(Following|Followers)$/i.test(nextLine) || /^\d+$/.test(nextLine));
    
    const isUsername = (str: string) => /^@?[a-z0-9._]+$/i.test(str);
    
    // 2-line structure heuristic
    if (nextLine && !nextIsHeaderOrNumber && isUsername(nextLine)) {
        displayName = line;
        username = nextLine;
        i += 2;
    } else {
        // 1-line structure (glued or standalone)
        const match = line.match(/^(.*?)(@?[a-z0-9._]+)$/i);
        if (match && match[2].length > 0) {
            displayName = match[1].trim();
            username = match[2];
            if (!displayName) displayName = username;
        } else {
            displayName = line;
            username = line.replace(/\s+/g, '').toLowerCase(); 
        }
        i++;
    }
    
    username = username.replace(/^@/, '');
    
    // Filter purely numeric edge cases or generic bots
    if (/^\d+$/.test(username) || /^user\d+$/i.test(username)) {
       continue;
    }
    
    const node: UserNode = { displayName, username };
    result.allUsers.set(username, node);
    lastParsedNode = node;
    
    if (currentSubject && currentContext) {
        const rels = result.relationships.get(currentSubject);
        if (rels) {
            rels[currentContext].push(node);
        }
    }
  }
  
  return result;
}

export interface MemberMetrics {
  username: string;
  inDegree: number;
  outDegree: number;
  mutuals: number;
  score: number;
  isAltCandidate?: boolean;
  altOf?: string;
  primaryCenter?: string;
}

export function findShortestPath(data: ParseResult, start: string, end: string): string[] | null {
  if (start === end) return [start];

  // Adjacency list from all relationships
  const adj = new Map<string, Set<string>>();
  
  const addEdge = (u: string, v: string) => {
    if (!adj.has(u)) adj.set(u, new Set());
    adj.get(u)!.add(v);
  };

  data.relationships.forEach((rels, subject) => {
    rels.following.forEach(u => addEdge(subject, u.username));
    rels.followers.forEach(u => addEdge(u.username, subject));
  });

  const queue: [string, string[]][] = [[start, [start]]];
  const visited = new Set<string>([start]);

  while (queue.length > 0) {
    const [node, path] = queue.shift()!;
    if (node === end) return path;

    const neighbors = adj.get(node) || new Set();
    for (const neighbor of neighbors) {
      if (!visited.has(neighbor)) {
        visited.add(neighbor);
        queue.push([neighbor, [...path, neighbor]]);
      }
    }
  }

  return null;
}

export function getCoreMembers(data: ParseResult): MemberMetrics[] {
  const metrics = new Map<string, MemberMetrics>();

  const getOrCreate = (username: string) => {
    if (!metrics.has(username)) {
      metrics.set(username, { username, inDegree: 0, outDegree: 0, mutuals: 0, score: 0 });
    }
    return metrics.get(username)!;
  };

  // Build a set of connections for quick mutual lookup
  const outwardEdges = new Map<string, Set<string>>();

  for (const [subject, rels] of data.relationships.entries()) {
    if (!outwardEdges.has(subject)) outwardEdges.set(subject, new Set());
    const subjectOut = outwardEdges.get(subject)!;

    for (const u of rels.following) {
       subjectOut.add(u.username);
    }
  }

  const centerRep = new Map<string, Map<string, number>>();

  // Calculate degrees and center reps
  for (const [subject, rels] of data.relationships.entries()) {
    const subjNode = getOrCreate(subject);
    
    for (const u of rels.following) {
      subjNode.outDegree++;
      const targetNode = getOrCreate(u.username);
      targetNode.inDegree++;
      
      if (!centerRep.has(u.username)) centerRep.set(u.username, new Map());
      centerRep.get(u.username)!.set(subject, (centerRep.get(u.username)!.get(subject) || 0) + 1);
    }

    for (const u of rels.followers) {
      subjNode.inDegree++;
      const sourceNode = getOrCreate(u.username);
      sourceNode.outDegree++;

      if (!centerRep.has(u.username)) centerRep.set(u.username, new Map());
      centerRep.get(u.username)!.set(subject, (centerRep.get(u.username)!.get(subject) || 0) + 1);

      if (outwardEdges.get(subject)?.has(u.username)) {
          subjNode.mutuals++;
          sourceNode.mutuals++;
      }
    }
  }

  // Calculate a simplified eigenvector-like centrality score
  // Degree + (mutuals * 3)
  for (const m of metrics.values()) {
    m.score = m.inDegree + m.outDegree + (m.mutuals * 3);
    
    // Assign primary center
    if (centerRep.has(m.username)) {
        const reps = Array.from(centerRep.get(m.username)!.entries());
        reps.sort((a, b) => b[1] - a[1]);
        if (reps.length > 0) m.primaryCenter = reps[0][0];
    } else if (data.relationships.has(m.username)) {
         m.primaryCenter = m.username;
    }
  }

  const sorted = Array.from(metrics.values()).sort((a, b) => b.score - a.score);

  // Advanced Algorithm: Alt Detection Heuristic
  for (let i = 0; i < sorted.length; i++) {
    for (let j = i + 1; j < sorted.length; j++) {
      const u1 = sorted[i].username.toLowerCase();
      const u2 = sorted[j].username.toLowerCase();
      if (u1.length < 3 || u2.length < 3) continue;

      // Substring match or common prefix/suffix
      const isSimilar = u1.includes(u2) || u2.includes(u1) || 
                       (u1.slice(0, 5) === u2.slice(0, 5) && Math.abs(u1.length - u2.length) < 3);

      if (isSimilar) {
        // High mutual connection similarity also helps
        const s1 = outwardEdges.get(u1) || new Set();
        const s2 = outwardEdges.get(u2) || new Set();
        let intersection = 0;
        s1.forEach(x => { if (s2.has(x)) intersection++; });
        const union = s1.size + s2.size - intersection;
        const jaccard = union > 0 ? intersection / union : 0;

        if (jaccard > 0.3 || (isSimilar && (s1.size < 5 || s2.size < 5))) {
            if (!sorted[j].isAltCandidate) {
              sorted[j].isAltCandidate = true;
              sorted[j].altOf = u1;
            }
        }
      }
    }
  }

  return sorted;
}

export interface ClusterInfo {
  center: string;
  members: string[];
  color: string;
}

export function detectClusters(data: ParseResult, metrics: MemberMetrics[]): ClusterInfo[] {
  const centers = Array.from(data.relationships.keys());
  const clusters = new Map<string, string[]>();
  
  centers.forEach(c => clusters.set(c, [c]));
  
  metrics.forEach(m => {
    if (m.primaryCenter && m.primaryCenter !== m.username) {
      if (clusters.has(m.primaryCenter)) {
        clusters.get(m.primaryCenter)!.push(m.username);
      }
    }
  });

  const colors = ["#6366f1", "#0ea5e9", "#10b981", "#f59e0b", "#ef4444", "#8b5cf6", "#ec4899", "#14b8a6", "#f97316"];
  
  return Array.from(clusters.entries())
    .map(([center, members], idx) => ({
      center,
      members,
      color: colors[idx % colors.length]
    }))
    .filter(c => c.members.length > 2)
    .sort((a, b) => b.members.length - a.members.length);
}